Mustache.php 12 KB

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