Mustache.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. /**
  3. * A Mustache implementation in PHP.
  4. *
  5. * {@link http://defunkt.github.com/mustache}
  6. *
  7. * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
  8. * logic from template files. In fact, it is not even possible to embed logic in the template.
  9. *
  10. * This is very, very rad.
  11. *
  12. * @author Justin Hileman {@link http://justinhileman.com}
  13. */
  14. class Mustache {
  15. public $_otag = '{{';
  16. public $_ctag = '}}';
  17. /**
  18. * Should this Mustache throw exceptions when it finds unexpected tags?
  19. *
  20. * @see self::_throwsException()
  21. */
  22. protected $_throwsExceptions = array(
  23. MustacheException::UNKNOWN_VARIABLE => false,
  24. MustacheException::UNCLOSED_SECTION => true,
  25. MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  26. MustacheException::UNKNOWN_PARTIAL => false,
  27. MustacheException::UNKNOWN_PRAGMA => true,
  28. );
  29. // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8.
  30. protected $_charset = 'UTF-8';
  31. const PRAGMA_DOT_NOTATION = 'DOT-NOTATION';
  32. /**
  33. * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}}
  34. * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be
  35. * escaped while the {{{unescaped}}} tag will be escaped.
  36. *
  37. * Pragmas apply only to the current template. Partials, even those included after the
  38. * {{%UNESCAPED}} call, will need their own pragma declaration.
  39. *
  40. * This may be useful in non-HTML Mustache situations.
  41. */
  42. const PRAGMA_UNESCAPED = 'UNESCAPED';
  43. protected $_tagRegEx;
  44. protected $_template = '';
  45. protected $_context = array();
  46. protected $_partials = array();
  47. protected $_pragmas = array();
  48. protected $_pragmasImplemented = array(
  49. self::PRAGMA_DOT_NOTATION,
  50. self::PRAGMA_UNESCAPED
  51. );
  52. protected $_localPragmas;
  53. /**
  54. * Mustache class constructor.
  55. *
  56. * This method accepts a $template string and a $view object. Optionally, pass an associative
  57. * array of partials as well.
  58. *
  59. * @access public
  60. * @param string $template (default: null)
  61. * @param mixed $view (default: null)
  62. * @param array $partials (default: null)
  63. * @return void
  64. */
  65. public function __construct($template = null, $view = null, $partials = null) {
  66. if ($template !== null) $this->_template = $template;
  67. if ($partials !== null) $this->_partials = $partials;
  68. if ($view !== null) $this->_context = array($view);
  69. }
  70. /**
  71. * Mustache class clone method.
  72. *
  73. * A cloned Mustache instance should have pragmas, delimeters and root context
  74. * reset to default values.
  75. *
  76. * @access public
  77. * @return void
  78. */
  79. public function __clone() {
  80. $this->_otag = '{{';
  81. $this->_ctag = '}}';
  82. $this->_localPragmas = null;
  83. if ($keys = array_keys($this->_context)) {
  84. $last = array_pop($keys);
  85. if ($this->_context[$last] instanceof Mustache) {
  86. $this->_context[$last] =& $this;
  87. }
  88. }
  89. }
  90. /**
  91. * Render the given template and view object.
  92. *
  93. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  94. * Optionally, pass an associative array of partials as well.
  95. *
  96. * @access public
  97. * @param string $template (default: null)
  98. * @param mixed $view (default: null)
  99. * @param array $partials (default: null)
  100. * @return string Rendered Mustache template.
  101. */
  102. public function render($template = null, $view = null, $partials = null) {
  103. if ($template === null) $template = $this->_template;
  104. if ($partials !== null) $this->_partials = $partials;
  105. if ($view) {
  106. $this->_context = array($view);
  107. } else if (empty($this->_context)) {
  108. $this->_context = array($this);
  109. }
  110. $template = $this->_renderPragmas($template);
  111. return $this->_renderTemplate($template, $this->_context);
  112. }
  113. /**
  114. * Wrap the render() function for string conversion.
  115. *
  116. * @access public
  117. * @return string
  118. */
  119. public function __toString() {
  120. // PHP doesn't like exceptions in __toString.
  121. // catch any exceptions and convert them to strings.
  122. try {
  123. $result = $this->render();
  124. return $result;
  125. } catch (Exception $e) {
  126. return "Error rendering mustache: " . $e->getMessage();
  127. }
  128. }
  129. /**
  130. * Internal render function, used for recursive calls.
  131. *
  132. * @access protected
  133. * @param string $template
  134. * @return string Rendered Mustache template.
  135. */
  136. protected function _renderTemplate($template) {
  137. $template = $this->_renderSection($template);
  138. return $this->_renderTags($template);
  139. }
  140. /**
  141. * Render boolean, enumerable and inverted sections.
  142. *
  143. * @access protected
  144. * @param string $template
  145. * @return string
  146. */
  147. protected function _renderSection($template) {
  148. $otag = preg_quote($this->_otag, '/');
  149. $ctag = preg_quote($this->_ctag, '/');
  150. $regex = '/' . $otag . '(\\^|\\#)\\s*(.+?)\\s*' . $ctag . '\\s*([\\s\\S]+?)' . $otag . '\\/\\s*\\2\\s*' . $ctag . '\\s*/m';
  151. $matches = array();
  152. while (preg_match($regex, $template, $matches, PREG_OFFSET_CAPTURE)) {
  153. $section = $matches[0][0];
  154. $offset = $matches[0][1];
  155. $type = $matches[1][0];
  156. $tag_name = trim($matches[2][0]);
  157. $content = $matches[3][0];
  158. $replace = '';
  159. $val = $this->_getVariable($tag_name);
  160. switch($type) {
  161. // inverted section
  162. case '^':
  163. if (empty($val)) {
  164. $replace .= $content;
  165. }
  166. break;
  167. // regular section
  168. case '#':
  169. if ($val) {
  170. // higher order sections
  171. if (is_callable($val)) {
  172. $content = call_user_func($val, $content);
  173. $replace .= $this->_renderTemplate($content);
  174. } else if ($this->_varIsIterable($val)) {
  175. foreach ($val as $local_context) {
  176. $this->_pushContext($local_context);
  177. $replace .= $this->_renderTemplate($content);
  178. $this->_popContext();
  179. }
  180. } else {
  181. if (is_array($val) || is_object($val)) {
  182. $this->_pushContext($val);
  183. $replace .= $this->_renderTemplate($content);
  184. $this->_popContext();
  185. } else {
  186. $replace .= $content;
  187. }
  188. }
  189. }
  190. break;
  191. }
  192. $template = substr_replace($template, $replace, $offset, strlen($section));
  193. }
  194. return $template;
  195. }
  196. /**
  197. * Initialize pragmas and remove all pragma tags.
  198. *
  199. * @access protected
  200. * @param string $template
  201. * @return string
  202. */
  203. protected function _renderPragmas($template) {
  204. $this->_localPragmas = $this->_pragmas;
  205. // no pragmas
  206. if (strpos($template, $this->_otag . '%') === false) {
  207. return $template;
  208. }
  209. $otag = preg_quote($this->_otag, '/');
  210. $ctag = preg_quote($this->_ctag, '/');
  211. $regex = '/' . $otag . '%\\s*([\\w_-]+)((?: [\\w]+=[\\w]+)*)\\s*' . $ctag . '\\n?/';
  212. return preg_replace_callback($regex, array($this, '_renderPragma'), $template);
  213. }
  214. /**
  215. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  216. *
  217. * @access protected
  218. * @param mixed $matches
  219. * @return void
  220. * @throws MustacheException unknown pragma
  221. */
  222. protected function _renderPragma($matches) {
  223. $pragma = $matches[0];
  224. $pragma_name = $matches[1];
  225. $options_string = $matches[2];
  226. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  227. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  228. }
  229. $options = array();
  230. foreach (explode(' ', trim($options_string)) as $o) {
  231. if ($p = trim($o)) {
  232. $p = explode('=', trim($p));
  233. $options[$p[0]] = $p[1];
  234. }
  235. }
  236. if (empty($options)) {
  237. $this->_localPragmas[$pragma_name] = true;
  238. } else {
  239. $this->_localPragmas[$pragma_name] = $options;
  240. }
  241. return '';
  242. }
  243. /**
  244. * Check whether this Mustache has a specific pragma.
  245. *
  246. * @access protected
  247. * @param string $pragma_name
  248. * @return bool
  249. */
  250. protected function _hasPragma($pragma_name) {
  251. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  252. return true;
  253. } else {
  254. return false;
  255. }
  256. }
  257. /**
  258. * Return pragma options, if any.
  259. *
  260. * @access protected
  261. * @param string $pragma_name
  262. * @return mixed
  263. * @throws MustacheException Unknown pragma
  264. */
  265. protected function _getPragmaOptions($pragma_name) {
  266. if (!$this->_hasPragma()) {
  267. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  268. }
  269. return $this->_localPragmas[$pragma_name];
  270. }
  271. /**
  272. * Check whether this Mustache instance throws a given exception.
  273. *
  274. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  275. *
  276. * @access protected
  277. * @param mixed $exception
  278. * @return void
  279. */
  280. protected function _throwsException($exception) {
  281. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  282. }
  283. /**
  284. * Loop through and render individual Mustache tags.
  285. *
  286. * @access protected
  287. * @param string $template
  288. * @return void
  289. */
  290. protected function _renderTags($template) {
  291. if (strpos($template, $this->_otag) === false) {
  292. return $template;
  293. }
  294. $otag_orig = $this->_otag;
  295. $ctag_orig = $this->_ctag;
  296. $otag = preg_quote($this->_otag, '/');
  297. $ctag = preg_quote($this->_ctag, '/');
  298. $this->_tagRegEx = '/' . $otag . "([#\^\/=!>\\{&])?(.+?)\\1?" . $ctag . "+/";
  299. $html = '';
  300. $matches = array();
  301. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  302. $tag = $matches[0][0];
  303. $offset = $matches[0][1];
  304. $modifier = $matches[1][0];
  305. $tag_name = trim($matches[2][0]);
  306. $html .= substr($template, 0, $offset);
  307. $html .= $this->_renderTag($modifier, $tag_name);
  308. $template = substr($template, $offset + strlen($tag));
  309. }
  310. $this->_otag = $otag_orig;
  311. $this->_ctag = $ctag_orig;
  312. return $html . $template;
  313. }
  314. /**
  315. * Render the named tag, given the specified modifier.
  316. *
  317. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  318. * `{` or `&` (don't escape output), or none (render escaped output).
  319. *
  320. * @access protected
  321. * @param string $modifier
  322. * @param string $tag_name
  323. * @throws MustacheException Unmatched section tag encountered.
  324. * @return string
  325. */
  326. protected function _renderTag($modifier, $tag_name) {
  327. switch ($modifier) {
  328. case '#':
  329. case '^':
  330. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  331. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  332. } else {
  333. return '';
  334. }
  335. break;
  336. case '/':
  337. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  338. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  339. } else {
  340. return '';
  341. }
  342. break;
  343. case '=':
  344. return $this->_changeDelimiter($tag_name);
  345. break;
  346. case '!':
  347. return $this->_renderComment($tag_name);
  348. break;
  349. case '>':
  350. return $this->_renderPartial($tag_name);
  351. break;
  352. case '{':
  353. case '&':
  354. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  355. return $this->_renderEscaped($tag_name);
  356. } else {
  357. return $this->_renderUnescaped($tag_name);
  358. }
  359. break;
  360. case '':
  361. default:
  362. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  363. return $this->_renderUnescaped($tag_name);
  364. } else {
  365. return $this->_renderEscaped($tag_name);
  366. }
  367. break;
  368. }
  369. }
  370. /**
  371. * Escape and return the requested tag.
  372. *
  373. * @access protected
  374. * @param string $tag_name
  375. * @return string
  376. */
  377. protected function _renderEscaped($tag_name) {
  378. return htmlentities($this->_getVariable($tag_name), null, $this->_charset);
  379. }
  380. /**
  381. * Render a comment (i.e. return an empty string).
  382. *
  383. * @access protected
  384. * @param string $tag_name
  385. * @return string
  386. */
  387. protected function _renderComment($tag_name) {
  388. return '';
  389. }
  390. /**
  391. * Return the requested tag unescaped.
  392. *
  393. * @access protected
  394. * @param string $tag_name
  395. * @return string
  396. */
  397. protected function _renderUnescaped($tag_name) {
  398. return $this->_getVariable($tag_name);
  399. }
  400. /**
  401. * Render the requested partial.
  402. *
  403. * @access protected
  404. * @param string $tag_name
  405. * @return string
  406. */
  407. protected function _renderPartial($tag_name) {
  408. $view = clone($this);
  409. return $view->render($this->_getPartial($tag_name));
  410. }
  411. /**
  412. * Change the Mustache tag delimiter. This method also replaces this object's current
  413. * tag RegEx with one using the new delimiters.
  414. *
  415. * @access protected
  416. * @param string $tag_name
  417. * @return string
  418. */
  419. protected function _changeDelimiter($tag_name) {
  420. $tags = explode(' ', $tag_name);
  421. $this->_otag = $tags[0];
  422. $this->_ctag = $tags[1];
  423. $otag = preg_quote($this->_otag, '/');
  424. $ctag = preg_quote($this->_ctag, '/');
  425. $this->_tagRegEx = '/' . $otag . "([#\^\/=!>\\{&])?(.+?)\\1?" . $ctag . "+/";
  426. return '';
  427. }
  428. /**
  429. * Push a local context onto the stack.
  430. *
  431. * @access protected
  432. * @param array &$local_context
  433. * @return void
  434. */
  435. protected function _pushContext(&$local_context) {
  436. $new = array();
  437. $new[] =& $local_context;
  438. foreach (array_keys($this->_context) as $key) {
  439. $new[] =& $this->_context[$key];
  440. }
  441. $this->_context = $new;
  442. }
  443. /**
  444. * Remove the latest context from the stack.
  445. *
  446. * @access protected
  447. * @return void
  448. */
  449. protected function _popContext() {
  450. $new = array();
  451. $keys = array_keys($this->_context);
  452. array_shift($keys);
  453. foreach ($keys as $key) {
  454. $new[] =& $this->_context[$key];
  455. }
  456. $this->_context = $new;
  457. }
  458. /**
  459. * Get a variable from the context array.
  460. *
  461. * If the view is an array, returns the value with array key $tag_name.
  462. * If the view is an object, this will check for a public member variable
  463. * named $tag_name. If none is available, this method will execute and return
  464. * any class method named $tag_name. Failing all of the above, this method will
  465. * return an empty string.
  466. *
  467. * @access protected
  468. * @param string $tag_name
  469. * @throws MustacheException Unknown variable name.
  470. * @return string
  471. */
  472. protected function _getVariable($tag_name) {
  473. if ($this->_hasPragma(self::PRAGMA_DOT_NOTATION)) {
  474. $chunks = explode('.', $tag_name);
  475. $first = array_shift($chunks);
  476. $ret = $this->_findVariableInContext($first, $this->_context);
  477. while ($next = array_shift($chunks)) {
  478. // Slice off a chunk of context for dot notation traversal.
  479. $c = array($ret);
  480. $ret = $this->_findVariableInContext($next, $c);
  481. }
  482. return $ret;
  483. } else {
  484. return $this->_findVariableInContext($tag_name, $this->_context);
  485. }
  486. }
  487. /**
  488. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  489. * variable traversal for dot notation.
  490. *
  491. * @access protected
  492. * @param string $tag_name
  493. * @param array $context
  494. * @throws MustacheException Unknown variable name.
  495. * @return string
  496. */
  497. protected function _findVariableInContext($tag_name, $context) {
  498. foreach ($context as $view) {
  499. if (is_object($view)) {
  500. if (isset($view->$tag_name)) {
  501. return $view->$tag_name;
  502. } else if (method_exists($view, $tag_name)) {
  503. return $view->$tag_name();
  504. }
  505. } else if (isset($view[$tag_name])) {
  506. return $view[$tag_name];
  507. }
  508. }
  509. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  510. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  511. } else {
  512. return '';
  513. }
  514. }
  515. /**
  516. * Retrieve the partial corresponding to the requested tag name.
  517. *
  518. * Silently fails (i.e. returns '') when the requested partial is not found.
  519. *
  520. * @access protected
  521. * @param string $tag_name
  522. * @throws MustacheException Unknown partial name.
  523. * @return string
  524. */
  525. protected function _getPartial($tag_name) {
  526. if (is_array($this->_partials) && isset($this->_partials[$tag_name])) {
  527. return $this->_partials[$tag_name];
  528. }
  529. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  530. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  531. } else {
  532. return '';
  533. }
  534. }
  535. /**
  536. * Check whether the given $var should be iterated (i.e. in a section context).
  537. *
  538. * @access protected
  539. * @param mixed $var
  540. * @return bool
  541. */
  542. protected function _varIsIterable($var) {
  543. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  544. }
  545. }
  546. /**
  547. * MustacheException class.
  548. *
  549. * @extends Exception
  550. */
  551. class MustacheException extends Exception {
  552. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  553. // in the current context.
  554. const UNKNOWN_VARIABLE = 0;
  555. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  556. const UNCLOSED_SECTION = 1;
  557. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  558. // without a corresponding {{#section}} or {{^section}}.
  559. const UNEXPECTED_CLOSE_SECTION = 2;
  560. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  561. // with no associated partial.
  562. const UNKNOWN_PARTIAL = 3;
  563. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  564. // which can't be handled by this Mustache instance.
  565. const UNKNOWN_PRAGMA = 4;
  566. }