Mustache.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. protected $tagRegEx;
  24. protected $template = '';
  25. protected $context = array();
  26. protected $partials = array();
  27. protected $pragmas = array();
  28. protected $pragmasImplemented = array('DOT-NOTATION');
  29. /**
  30. * Mustache class constructor.
  31. *
  32. * This method accepts a $template string and a $view object. Optionally, pass an associative
  33. * array of partials as well.
  34. *
  35. * @access public
  36. * @param string $template (default: null)
  37. * @param mixed $view (default: null)
  38. * @param array $partials (default: null)
  39. * @return void
  40. */
  41. public function __construct($template = null, $view = null, $partials = null) {
  42. if ($template !== null) $this->template = $template;
  43. if ($partials !== null) $this->partials = $partials;
  44. if ($view !== null) $this->context = array($view);
  45. }
  46. /**
  47. * Render the given template and view object.
  48. *
  49. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  50. * Optionally, pass an associative array of partials as well.
  51. *
  52. * @access public
  53. * @param string $template (default: null)
  54. * @param mixed $view (default: null)
  55. * @param array $partials (default: null)
  56. * @return string Rendered Mustache template.
  57. */
  58. public function render($template = null, $view = null, $partials = null) {
  59. if ($template === null) $template = $this->template;
  60. if ($partials !== null) $this->partials = $partials;
  61. if ($view) {
  62. $this->context = array($view);
  63. } else if (empty($this->context)) {
  64. $this->context = array($this);
  65. }
  66. return $this->_render($template, $this->context);
  67. }
  68. /**
  69. * Wrap the render() function for string conversion.
  70. *
  71. * @access public
  72. * @return string
  73. */
  74. public function __toString() {
  75. // PHP doesn't like exceptions in __toString.
  76. // catch any exceptions and convert them to strings.
  77. try {
  78. $result = $this->render();
  79. return $result;
  80. } catch (Exception $e) {
  81. return "Error rendering mustache: " . $e->getMessage();
  82. }
  83. }
  84. /**
  85. * Internal render function, used for recursive calls.
  86. *
  87. * @access protected
  88. * @param string $template
  89. * @param array &$context
  90. * @return string Rendered Mustache template.
  91. */
  92. protected function _render($template, &$context) {
  93. $template = $this->renderPragmas($template, $context);
  94. $template = $this->renderSection($template, $context);
  95. return $this->renderTags($template, $context);
  96. }
  97. /**
  98. * Render boolean, enumerable and inverted sections.
  99. *
  100. * @access protected
  101. * @param string $template
  102. * @param array $context
  103. * @return string
  104. */
  105. protected function renderSection($template, &$context) {
  106. if (strpos($template, $this->otag . '#') === false) {
  107. return $template;
  108. }
  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. * Loop through and render individual Mustache tags.
  196. *
  197. * @access protected
  198. * @param string $template
  199. * @param array $context
  200. * @return void
  201. */
  202. protected function renderTags($template, &$context) {
  203. if (strpos($template, $this->otag) === false) {
  204. return $template;
  205. }
  206. $otag = $this->prepareRegEx($this->otag);
  207. $ctag = $this->prepareRegEx($this->ctag);
  208. $this->tagRegEx = '/' . $otag . "(#|\/|=|!|>|\\{|&)?([^\/#]+?)\\1?" . $ctag . "+/";
  209. $html = '';
  210. $matches = array();
  211. while (preg_match($this->tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  212. $tag = $matches[0][0];
  213. $offset = $matches[0][1];
  214. $modifier = $matches[1][0];
  215. $tag_name = trim($matches[2][0]);
  216. $html .= substr($template, 0, $offset);
  217. $html .= $this->renderTag($modifier, $tag_name, $context);
  218. $template = substr($template, $offset + strlen($tag));
  219. }
  220. return $html . $template;
  221. }
  222. /**
  223. * Render the named tag, given the specified modifier.
  224. *
  225. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  226. * `{` or `&` (don't escape output), or none (render escaped output).
  227. *
  228. * @access protected
  229. * @param string $modifier
  230. * @param string $tag_name
  231. * @param array $context
  232. * @throws MustacheException Unmatched section tag encountered.
  233. * @return string
  234. */
  235. protected function renderTag($modifier, $tag_name, &$context) {
  236. switch ($modifier) {
  237. case '#':
  238. if ($this->throwSectionExceptions) {
  239. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  240. } else {
  241. return '';
  242. }
  243. break;
  244. case '/':
  245. if ($this->throwSectionExceptions) {
  246. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  247. } else {
  248. return '';
  249. }
  250. break;
  251. case '=':
  252. return $this->changeDelimiter($tag_name, $context);
  253. break;
  254. case '!':
  255. return $this->renderComment($tag_name, $context);
  256. break;
  257. case '>':
  258. return $this->renderPartial($tag_name, $context);
  259. break;
  260. case '{':
  261. case '&':
  262. return $this->renderUnescaped($tag_name, $context);
  263. break;
  264. case '':
  265. default:
  266. return $this->renderEscaped($tag_name, $context);
  267. break;
  268. }
  269. }
  270. /**
  271. * Escape and return the requested tag.
  272. *
  273. * @access protected
  274. * @param string $tag_name
  275. * @param array $context
  276. * @return string
  277. */
  278. protected function renderEscaped($tag_name, &$context) {
  279. return htmlentities($this->getVariable($tag_name, $context), null, $this->charset);
  280. }
  281. /**
  282. * Render a comment (i.e. return an empty string).
  283. *
  284. * @access protected
  285. * @param string $tag_name
  286. * @param array $context
  287. * @return string
  288. */
  289. protected function renderComment($tag_name, &$context) {
  290. return '';
  291. }
  292. /**
  293. * Return the requested tag unescaped.
  294. *
  295. * @access protected
  296. * @param string $tag_name
  297. * @param array $context
  298. * @return string
  299. */
  300. protected function renderUnescaped($tag_name, &$context) {
  301. return $this->getVariable($tag_name, $context);
  302. }
  303. /**
  304. * Render the requested partial.
  305. *
  306. * @access protected
  307. * @param string $tag_name
  308. * @param array $context
  309. * @return string
  310. */
  311. protected function renderPartial($tag_name, &$context) {
  312. $view = new self($this->getPartial($tag_name), $context, $this->partials);
  313. $view->otag = $this->otag;
  314. $view->ctag = $this->ctag;
  315. return $view->render();
  316. }
  317. /**
  318. * Change the Mustache tag delimiter. This method also replaces this object's current
  319. * tag RegEx with one using the new delimiters.
  320. *
  321. * @access protected
  322. * @param string $tag_name
  323. * @param array $context
  324. * @return string
  325. */
  326. protected function changeDelimiter($tag_name, &$context) {
  327. $tags = explode(' ', $tag_name);
  328. $this->otag = $tags[0];
  329. $this->ctag = $tags[1];
  330. $otag = $this->prepareRegEx($this->otag);
  331. $ctag = $this->prepareRegEx($this->ctag);
  332. $this->tagRegEx = '/' . $otag . "(#|\/|=|!|>|\\{|&)?([^\/#\^]+?)\\1?" . $ctag . "+/";
  333. return '';
  334. }
  335. /**
  336. * Prepare a new context reference array.
  337. *
  338. * This is used to create context arrays for iterable blocks.
  339. *
  340. * @access protected
  341. * @param array $context
  342. * @param mixed $local_context
  343. * @return void
  344. */
  345. protected function getContext(&$context, &$local_context) {
  346. $ret = array();
  347. $ret[] =& $local_context;
  348. foreach ($context as $view) {
  349. $ret[] =& $view;
  350. }
  351. return $ret;
  352. }
  353. /**
  354. * Get a variable from the context array.
  355. *
  356. * If the view is an array, returns the value with array key $tag_name.
  357. * If the view is an object, this will check for a public member variable
  358. * named $tag_name. If none is available, this method will execute and return
  359. * any class method named $tag_name. Failing all of the above, this method will
  360. * return an empty string.
  361. *
  362. * @access protected
  363. * @param string $tag_name
  364. * @param array $context
  365. * @throws MustacheException Unknown variable name.
  366. * @return string
  367. */
  368. protected function getVariable($tag_name, &$context) {
  369. foreach ($context as $view) {
  370. if (is_object($view)) {
  371. if (isset($view->$tag_name)) {
  372. return $view->$tag_name;
  373. } else if (method_exists($view, $tag_name)) {
  374. return $view->$tag_name();
  375. }
  376. } else if (isset($view[$tag_name])) {
  377. return $view[$tag_name];
  378. }
  379. }
  380. if ($this->throwVariableExceptions) {
  381. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  382. } else {
  383. return '';
  384. }
  385. }
  386. /**
  387. * Retrieve the partial corresponding to the requested tag name.
  388. *
  389. * Silently fails (i.e. returns '') when the requested partial is not found.
  390. *
  391. * @access protected
  392. * @param string $tag_name
  393. * @throws MustacheException Unknown partial name.
  394. * @return string
  395. */
  396. protected function getPartial($tag_name) {
  397. if (is_array($this->partials) && isset($this->partials[$tag_name])) {
  398. return $this->partials[$tag_name];
  399. }
  400. if ($this->throwPartialExceptions) {
  401. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  402. } else {
  403. return '';
  404. }
  405. }
  406. /**
  407. * Check whether the given $var should be iterated (i.e. in a section context).
  408. *
  409. * @access protected
  410. * @param mixed $var
  411. * @return bool
  412. */
  413. protected function varIsIterable($var) {
  414. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  415. }
  416. /**
  417. * Prepare a string to be used in a regular expression.
  418. *
  419. * @access protected
  420. * @param string $str
  421. * @return string
  422. */
  423. protected function prepareRegEx($str) {
  424. $replace = array(
  425. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  426. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  427. '{' => '\{', '}' => '\}', ',' => '\,'
  428. );
  429. return strtr($str, $replace);
  430. }
  431. }
  432. /**
  433. * MustacheException class.
  434. *
  435. * @extends Exception
  436. */
  437. class MustacheException extends Exception {
  438. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  439. // in the current context.
  440. const UNKNOWN_VARIABLE = 0;
  441. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  442. const UNCLOSED_SECTION = 1;
  443. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  444. // without a corresponding {{#section}}.
  445. const UNEXPECTED_CLOSE_SECTION = 2;
  446. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  447. // with no associated partial.
  448. const UNKNOWN_PARTIAL = 3;
  449. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  450. // which can't be handled by this Mustache instance.
  451. const UNKNOWN_PRAGMA = 4;
  452. }