Mustache.php 17 KB

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