Mustache.php 15 KB

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