Mustache.php 12 KB

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