Mustache.php 15 KB

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