Mustache.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. $replace .= $this->_render($content, $this->getContext($context, $val));
  153. } else {
  154. $replace .= $content;
  155. }
  156. }
  157. break;
  158. }
  159. $template = substr_replace($template, $replace, $offset, strlen($section));
  160. }
  161. return $template;
  162. }
  163. /**
  164. * Initialize pragmas and remove all pragma tags.
  165. *
  166. * @access protected
  167. * @param string $template
  168. * @param array &$context
  169. * @return string
  170. */
  171. protected function renderPragmas($template, &$context) {
  172. // no pragmas
  173. if (strpos($template, $this->otag . '%') === false) {
  174. return $template;
  175. }
  176. $otag = $this->prepareRegEx($this->otag);
  177. $ctag = $this->prepareRegEx($this->ctag);
  178. $regex = '/' . $otag . '%\\s*([\\w_-]+)((?: [\\w]+=[\\w]+)*)\\s*' . $ctag . '\\n?/';
  179. return preg_replace_callback($regex, array($this, 'renderPragma'), $template);
  180. }
  181. /**
  182. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  183. *
  184. * @access protected
  185. * @param mixed $matches
  186. * @return void
  187. * @throws MustacheException unknown pragma
  188. */
  189. protected function renderPragma($matches) {
  190. $pragma = $matches[0];
  191. $pragma_name = $matches[1];
  192. $options_string = $matches[2];
  193. if (!in_array($pragma_name, $this->pragmasImplemented)) {
  194. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  195. }
  196. $options = array();
  197. foreach (explode(' ', trim($options_string)) as $o) {
  198. if ($p = trim($o)) {
  199. $p = explode('=', trim($p));
  200. $options[$p[0]] = $p[1];
  201. }
  202. }
  203. if (empty($options)) {
  204. $this->pragmas[$pragma_name] = true;
  205. } else {
  206. $this->pragmas[$pragma_name] = $options;
  207. }
  208. return '';
  209. }
  210. protected function hasPragma($pragma_name) {
  211. if (array_key_exists($pragma_name, $this->pragmas) && $this->pragmas[$pragma_name]) {
  212. return true;
  213. }
  214. }
  215. protected function getPragmaOptions($pragma_name) {
  216. if (!$this->hasPragma()) {
  217. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  218. }
  219. return $this->pragmas[$pragma_name];
  220. }
  221. /**
  222. * Loop through and render individual Mustache tags.
  223. *
  224. * @access protected
  225. * @param string $template
  226. * @param array $context
  227. * @return void
  228. */
  229. protected function renderTags($template, &$context) {
  230. if (strpos($template, $this->otag) === false) {
  231. return $template;
  232. }
  233. $otag = $this->prepareRegEx($this->otag);
  234. $ctag = $this->prepareRegEx($this->ctag);
  235. $this->tagRegEx = '/' . $otag . "(#|\/|=|!|>|\\{|&)?([^\/#]+?)\\1?" . $ctag . "+/";
  236. $html = '';
  237. $matches = array();
  238. while (preg_match($this->tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  239. $tag = $matches[0][0];
  240. $offset = $matches[0][1];
  241. $modifier = $matches[1][0];
  242. $tag_name = trim($matches[2][0]);
  243. $html .= substr($template, 0, $offset);
  244. $html .= $this->renderTag($modifier, $tag_name, $context);
  245. $template = substr($template, $offset + strlen($tag));
  246. }
  247. return $html . $template;
  248. }
  249. /**
  250. * Render the named tag, given the specified modifier.
  251. *
  252. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  253. * `{` or `&` (don't escape output), or none (render escaped output).
  254. *
  255. * @access protected
  256. * @param string $modifier
  257. * @param string $tag_name
  258. * @param array $context
  259. * @throws MustacheException Unmatched section tag encountered.
  260. * @return string
  261. */
  262. protected function renderTag($modifier, $tag_name, &$context) {
  263. switch ($modifier) {
  264. case '#':
  265. if ($this->throwSectionExceptions) {
  266. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  267. } else {
  268. return '';
  269. }
  270. break;
  271. case '/':
  272. if ($this->throwSectionExceptions) {
  273. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  274. } else {
  275. return '';
  276. }
  277. break;
  278. case '=':
  279. return $this->changeDelimiter($tag_name, $context);
  280. break;
  281. case '!':
  282. return $this->renderComment($tag_name, $context);
  283. break;
  284. case '>':
  285. return $this->renderPartial($tag_name, $context);
  286. break;
  287. case '{':
  288. case '&':
  289. if ($this->hasPragma(self::PRAGMA_UNESCAPED)) {
  290. return $this->renderEscaped($tag_name, $context);
  291. } else {
  292. return $this->renderUnescaped($tag_name, $context);
  293. }
  294. break;
  295. case '':
  296. default:
  297. if ($this->hasPragma(self::PRAGMA_UNESCAPED)) {
  298. return $this->renderUnescaped($tag_name, $context);
  299. } else {
  300. return $this->renderEscaped($tag_name, $context);
  301. }
  302. break;
  303. }
  304. }
  305. /**
  306. * Escape and return the requested tag.
  307. *
  308. * @access protected
  309. * @param string $tag_name
  310. * @param array $context
  311. * @return string
  312. */
  313. protected function renderEscaped($tag_name, &$context) {
  314. return htmlentities($this->getVariable($tag_name, $context), null, $this->charset);
  315. }
  316. /**
  317. * Render a comment (i.e. return an empty string).
  318. *
  319. * @access protected
  320. * @param string $tag_name
  321. * @param array $context
  322. * @return string
  323. */
  324. protected function renderComment($tag_name, &$context) {
  325. return '';
  326. }
  327. /**
  328. * Return the requested tag unescaped.
  329. *
  330. * @access protected
  331. * @param string $tag_name
  332. * @param array $context
  333. * @return string
  334. */
  335. protected function renderUnescaped($tag_name, &$context) {
  336. return $this->getVariable($tag_name, $context);
  337. }
  338. /**
  339. * Render the requested partial.
  340. *
  341. * @access protected
  342. * @param string $tag_name
  343. * @param array $context
  344. * @return string
  345. */
  346. protected function renderPartial($tag_name, &$context) {
  347. $view = new self($this->getPartial($tag_name), $context, $this->partials);
  348. $view->otag = $this->otag;
  349. $view->ctag = $this->ctag;
  350. return $view->render();
  351. }
  352. /**
  353. * Change the Mustache tag delimiter. This method also replaces this object's current
  354. * tag RegEx with one using the new delimiters.
  355. *
  356. * @access protected
  357. * @param string $tag_name
  358. * @param array $context
  359. * @return string
  360. */
  361. protected function changeDelimiter($tag_name, &$context) {
  362. $tags = explode(' ', $tag_name);
  363. $this->otag = $tags[0];
  364. $this->ctag = $tags[1];
  365. $otag = $this->prepareRegEx($this->otag);
  366. $ctag = $this->prepareRegEx($this->ctag);
  367. $this->tagRegEx = '/' . $otag . "(#|\/|=|!|>|\\{|&)?([^\/#\^]+?)\\1?" . $ctag . "+/";
  368. return '';
  369. }
  370. /**
  371. * Prepare a new context reference array.
  372. *
  373. * This is used to create context arrays for iterable blocks.
  374. *
  375. * @access protected
  376. * @param array $context
  377. * @param mixed $local_context
  378. * @return void
  379. */
  380. protected function getContext(&$context, &$local_context) {
  381. $ret = array();
  382. $ret[] =& $local_context;
  383. foreach ($context as $view) {
  384. $ret[] =& $view;
  385. }
  386. return $ret;
  387. }
  388. /**
  389. * Get a variable from the context array.
  390. *
  391. * If the view is an array, returns the value with array key $tag_name.
  392. * If the view is an object, this will check for a public member variable
  393. * named $tag_name. If none is available, this method will execute and return
  394. * any class method named $tag_name. Failing all of the above, this method will
  395. * return an empty string.
  396. *
  397. * @access protected
  398. * @param string $tag_name
  399. * @param array $context
  400. * @throws MustacheException Unknown variable name.
  401. * @return string
  402. */
  403. protected function getVariable($tag_name, &$context) {
  404. if ($this->hasPragma(self::PRAGMA_DOT_NOTATION)) {
  405. $chunks = explode('.', $tag_name);
  406. $first = array_shift($chunks);
  407. $ret = $this->_getVariable($first, $context);
  408. while ($next = array_shift($chunks)) {
  409. // Slice off a chunk of context for dot notation traversal.
  410. $c = array($ret);
  411. $ret = $this->_getVariable($next, $c);
  412. }
  413. return $ret;
  414. } else {
  415. return $this->_getVariable($tag_name, $context);
  416. }
  417. }
  418. /**
  419. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  420. * variable traversal for dot notation.
  421. *
  422. * @access protected
  423. * @param string $tag_name
  424. * @param array &$context
  425. * @throws MustacheException Unknown variable name.
  426. * @return string
  427. */
  428. protected function _getVariable($tag_name, &$context) {
  429. foreach ($context as $view) {
  430. if (is_object($view)) {
  431. if (isset($view->$tag_name)) {
  432. return $view->$tag_name;
  433. } else if (method_exists($view, $tag_name)) {
  434. return $view->$tag_name();
  435. }
  436. } else if (isset($view[$tag_name])) {
  437. return $view[$tag_name];
  438. }
  439. }
  440. if ($this->throwVariableExceptions) {
  441. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  442. } else {
  443. return '';
  444. }
  445. }
  446. /**
  447. * Retrieve the partial corresponding to the requested tag name.
  448. *
  449. * Silently fails (i.e. returns '') when the requested partial is not found.
  450. *
  451. * @access protected
  452. * @param string $tag_name
  453. * @throws MustacheException Unknown partial name.
  454. * @return string
  455. */
  456. protected function getPartial($tag_name) {
  457. if (is_array($this->partials) && isset($this->partials[$tag_name])) {
  458. return $this->partials[$tag_name];
  459. }
  460. if ($this->throwPartialExceptions) {
  461. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  462. } else {
  463. return '';
  464. }
  465. }
  466. /**
  467. * Check whether the given $var should be iterated (i.e. in a section context).
  468. *
  469. * @access protected
  470. * @param mixed $var
  471. * @return bool
  472. */
  473. protected function varIsIterable($var) {
  474. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  475. }
  476. /**
  477. * Prepare a string to be used in a regular expression.
  478. *
  479. * @access protected
  480. * @param string $str
  481. * @return string
  482. */
  483. protected function prepareRegEx($str) {
  484. $replace = array(
  485. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  486. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  487. '{' => '\{', '}' => '\}', ',' => '\,'
  488. );
  489. return strtr($str, $replace);
  490. }
  491. }
  492. /**
  493. * MustacheException class.
  494. *
  495. * @extends Exception
  496. */
  497. class MustacheException extends Exception {
  498. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  499. // in the current context.
  500. const UNKNOWN_VARIABLE = 0;
  501. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  502. const UNCLOSED_SECTION = 1;
  503. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  504. // without a corresponding {{#section}}.
  505. const UNEXPECTED_CLOSE_SECTION = 2;
  506. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  507. // with no associated partial.
  508. const UNKNOWN_PARTIAL = 3;
  509. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  510. // which can't be handled by this Mustache instance.
  511. const UNKNOWN_PRAGMA = 4;
  512. }