Mustache.php 19 KB

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