Mustache.php 17 KB

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