Mustache.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. /**
  195. * Check whether this Mustache has a specific pragma.
  196. *
  197. * @access protected
  198. * @param string $pragma_name
  199. * @return bool
  200. */
  201. protected function hasPragma($pragma_name) {
  202. if (array_key_exists($pragma_name, $this->_pragmas) && $this->_pragmas[$pragma_name]) {
  203. return true;
  204. } else {
  205. return false;
  206. }
  207. }
  208. /**
  209. * Return pragma options, if any.
  210. *
  211. * @access protected
  212. * @param string $pragma_name
  213. * @return mixed
  214. * @throws MustacheException Unknown pragma
  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. case '^':
  267. if ($this->throwSectionExceptions) {
  268. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  269. } else {
  270. return '';
  271. }
  272. break;
  273. case '/':
  274. if ($this->throwSectionExceptions) {
  275. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  276. } else {
  277. return '';
  278. }
  279. break;
  280. case '=':
  281. return $this->changeDelimiter($tag_name, $context);
  282. break;
  283. case '!':
  284. return $this->renderComment($tag_name, $context);
  285. break;
  286. case '>':
  287. return $this->renderPartial($tag_name, $context);
  288. break;
  289. case '{':
  290. case '&':
  291. return $this->renderUnescaped($tag_name, $context);
  292. break;
  293. case '':
  294. default:
  295. return $this->renderEscaped($tag_name, $context);
  296. break;
  297. }
  298. }
  299. /**
  300. * Escape and return the requested tag.
  301. *
  302. * @access protected
  303. * @param string $tag_name
  304. * @param array $context
  305. * @return string
  306. */
  307. protected function renderEscaped($tag_name, &$context) {
  308. return htmlentities($this->getVariable($tag_name, $context), null, $this->_charset);
  309. }
  310. /**
  311. * Render a comment (i.e. return an empty string).
  312. *
  313. * @access protected
  314. * @param string $tag_name
  315. * @param array $context
  316. * @return string
  317. */
  318. protected function renderComment($tag_name, &$context) {
  319. return '';
  320. }
  321. /**
  322. * Return the requested tag unescaped.
  323. *
  324. * @access protected
  325. * @param string $tag_name
  326. * @param array $context
  327. * @return string
  328. */
  329. protected function renderUnescaped($tag_name, &$context) {
  330. return $this->getVariable($tag_name, $context);
  331. }
  332. /**
  333. * Render the requested partial.
  334. *
  335. * @access protected
  336. * @param string $tag_name
  337. * @param array $context
  338. * @return string
  339. */
  340. protected function renderPartial($tag_name, &$context) {
  341. $view = new self($this->getPartial($tag_name), $context, $this->_partials);
  342. $view->_otag = $this->_otag;
  343. $view->_ctag = $this->_ctag;
  344. return $view->render();
  345. }
  346. /**
  347. * Change the Mustache tag delimiter. This method also replaces this object's current
  348. * tag RegEx with one using the new delimiters.
  349. *
  350. * @access protected
  351. * @param string $tag_name
  352. * @param array $context
  353. * @return string
  354. */
  355. protected function changeDelimiter($tag_name, &$context) {
  356. $tags = explode(' ', $tag_name);
  357. $this->_otag = $tags[0];
  358. $this->_ctag = $tags[1];
  359. $otag = $this->prepareRegEx($this->_otag);
  360. $ctag = $this->prepareRegEx($this->_ctag);
  361. $this->_tagRegEx = '/' . $otag . "([#\^\/=!>\\{&])?(.+?)\\1?" . $ctag . "+/";
  362. return '';
  363. }
  364. /**
  365. * Prepare a new context reference array.
  366. *
  367. * This is used to create context arrays for iterable blocks.
  368. *
  369. * @access protected
  370. * @param array $context
  371. * @param mixed $local_context
  372. * @return void
  373. */
  374. protected function getContext(&$context, &$local_context) {
  375. $ret = array();
  376. $ret[] =& $local_context;
  377. foreach ($context as $view) {
  378. $ret[] =& $view;
  379. }
  380. return $ret;
  381. }
  382. /**
  383. * Get a variable from the context array.
  384. *
  385. * If the view is an array, returns the value with array key $tag_name.
  386. * If the view is an object, this will check for a public member variable
  387. * named $tag_name. If none is available, this method will execute and return
  388. * any class method named $tag_name. Failing all of the above, this method will
  389. * return an empty string.
  390. *
  391. * @access protected
  392. * @param string $tag_name
  393. * @param array $context
  394. * @throws MustacheException Unknown variable name.
  395. * @return string
  396. */
  397. protected function getVariable($tag_name, &$context) {
  398. if ($this->hasPragma(self::PRAGMA_DOT_NOTATION)) {
  399. $chunks = explode('.', $tag_name);
  400. $first = array_shift($chunks);
  401. $ret = $this->_getVariable($first, $context);
  402. while ($next = array_shift($chunks)) {
  403. // Slice off a chunk of context for dot notation traversal.
  404. $c = array($ret);
  405. $ret = $this->_getVariable($next, $c);
  406. }
  407. return $ret;
  408. } else {
  409. return $this->_getVariable($tag_name, $context);
  410. }
  411. }
  412. /**
  413. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  414. * variable traversal for dot notation.
  415. *
  416. * @access protected
  417. * @param string $tag_name
  418. * @param array &$context
  419. * @throws MustacheException Unknown variable name.
  420. * @return string
  421. */
  422. protected function _getVariable($tag_name, &$context) {
  423. foreach ($context as $view) {
  424. if (is_object($view)) {
  425. if (isset($view->$tag_name)) {
  426. return $view->$tag_name;
  427. } else if (method_exists($view, $tag_name)) {
  428. return $view->$tag_name();
  429. }
  430. } else if (isset($view[$tag_name])) {
  431. return $view[$tag_name];
  432. }
  433. }
  434. if ($this->throwVariableExceptions) {
  435. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  436. } else {
  437. return '';
  438. }
  439. }
  440. /**
  441. * Retrieve the partial corresponding to the requested tag name.
  442. *
  443. * Silently fails (i.e. returns '') when the requested partial is not found.
  444. *
  445. * @access protected
  446. * @param string $tag_name
  447. * @throws MustacheException Unknown partial name.
  448. * @return string
  449. */
  450. protected function getPartial($tag_name) {
  451. if (is_array($this->_partials) && isset($this->_partials[$tag_name])) {
  452. return $this->_partials[$tag_name];
  453. }
  454. if ($this->throwPartialExceptions) {
  455. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  456. } else {
  457. return '';
  458. }
  459. }
  460. /**
  461. * Check whether the given $var should be iterated (i.e. in a section context).
  462. *
  463. * @access protected
  464. * @param mixed $var
  465. * @return bool
  466. */
  467. protected function varIsIterable($var) {
  468. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  469. }
  470. /**
  471. * Prepare a string to be used in a regular expression.
  472. *
  473. * @access protected
  474. * @param string $str
  475. * @return string
  476. */
  477. protected function prepareRegEx($str) {
  478. $replace = array(
  479. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  480. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  481. '{' => '\{', '}' => '\}', ',' => '\,'
  482. );
  483. return strtr($str, $replace);
  484. }
  485. }
  486. /**
  487. * MustacheException class.
  488. *
  489. * @extends Exception
  490. */
  491. class MustacheException extends Exception {
  492. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  493. // in the current context.
  494. const UNKNOWN_VARIABLE = 0;
  495. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  496. const UNCLOSED_SECTION = 1;
  497. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  498. // without a corresponding {{#section}}.
  499. const UNEXPECTED_CLOSE_SECTION = 2;
  500. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  501. // with no associated partial.
  502. const UNKNOWN_PARTIAL = 3;
  503. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  504. // which can't be handled by this Mustache instance.
  505. const UNKNOWN_PRAGMA = 4;
  506. }