Mustache.php 15 KB

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