Mustache.php 18 KB

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