Mustache.php 15 KB

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