Mustache.php 15 KB

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