Mustache.php 12 KB

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