Mustache.php 17 KB

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