Mustache.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. if ($this->throwSectionExceptions) {
  189. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  190. } else {
  191. return '';
  192. }
  193. break;
  194. case '/':
  195. if ($this->throwSectionExceptions) {
  196. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  197. } else {
  198. return '';
  199. }
  200. break;
  201. case '=':
  202. return $this->changeDelimiter($tag_name, $context);
  203. break;
  204. case '!':
  205. return $this->renderComment($tag_name, $context);
  206. break;
  207. case '>':
  208. return $this->renderPartial($tag_name, $context);
  209. break;
  210. case '{':
  211. case '&':
  212. return $this->renderUnescaped($tag_name, $context);
  213. break;
  214. case '':
  215. default:
  216. return $this->renderEscaped($tag_name, $context);
  217. break;
  218. }
  219. }
  220. /**
  221. * Escape and return the requested tag.
  222. *
  223. * @access protected
  224. * @param string $tag_name
  225. * @param array $context
  226. * @return string
  227. */
  228. protected function renderEscaped($tag_name, &$context) {
  229. return htmlentities($this->getVariable($tag_name, $context), null, $this->charset);
  230. }
  231. /**
  232. * Render a comment (i.e. return an empty string).
  233. *
  234. * @access protected
  235. * @param string $tag_name
  236. * @param array $context
  237. * @return string
  238. */
  239. protected function renderComment($tag_name, &$context) {
  240. return '';
  241. }
  242. /**
  243. * Return the requested tag unescaped.
  244. *
  245. * @access protected
  246. * @param string $tag_name
  247. * @param array $context
  248. * @return string
  249. */
  250. protected function renderUnescaped($tag_name, &$context) {
  251. return $this->getVariable($tag_name, $context);
  252. }
  253. /**
  254. * Render the requested partial.
  255. *
  256. * @access protected
  257. * @param string $tag_name
  258. * @param array $context
  259. * @return string
  260. */
  261. protected function renderPartial($tag_name, &$context) {
  262. $view = new self($this->getPartial($tag_name), $context, $this->partials);
  263. $view->otag = $this->otag;
  264. $view->ctag = $this->ctag;
  265. return $view->render();
  266. }
  267. /**
  268. * Change the Mustache tag delimiter. This method also replaces this object's current
  269. * tag RegEx with one using the new delimiters.
  270. *
  271. * @access protected
  272. * @param string $tag_name
  273. * @param array $context
  274. * @return string
  275. */
  276. protected function changeDelimiter($tag_name, &$context) {
  277. $tags = explode(' ', $tag_name);
  278. $this->otag = $tags[0];
  279. $this->ctag = $tags[1];
  280. $otag = $this->prepareRegEx($this->otag);
  281. $ctag = $this->prepareRegEx($this->ctag);
  282. $this->tagRegEx = '/' . $otag . "(#|\/|=|!|>|\\{|&)?([^\/#\^]+?)\\1?" . $ctag . "+/";
  283. return '';
  284. }
  285. /**
  286. * Prepare a new context reference array.
  287. *
  288. * This is used to create context arrays for iterable blocks.
  289. *
  290. * @access protected
  291. * @param array $context
  292. * @param mixed $local_context
  293. * @return void
  294. */
  295. protected function getContext(&$context, &$local_context) {
  296. $ret = array();
  297. $ret[] =& $local_context;
  298. foreach ($context as $view) {
  299. $ret[] =& $view;
  300. }
  301. return $ret;
  302. }
  303. /**
  304. * Get a variable from the context array.
  305. *
  306. * If the view is an array, returns the value with array key $tag_name.
  307. * If the view is an object, this will check for a public member variable
  308. * named $tag_name. If none is available, this method will execute and return
  309. * any class method named $tag_name. Failing all of the above, this method will
  310. * return an empty string.
  311. *
  312. * @access protected
  313. * @param string $tag_name
  314. * @param array $context
  315. * @throws MustacheException Unknown variable name.
  316. * @return string
  317. */
  318. protected function getVariable($tag_name, &$context) {
  319. foreach ($context as $view) {
  320. if (is_object($view)) {
  321. if (isset($view->$tag_name)) {
  322. return $view->$tag_name;
  323. } else if (method_exists($view, $tag_name)) {
  324. return $view->$tag_name();
  325. }
  326. } else if (isset($view[$tag_name])) {
  327. return $view[$tag_name];
  328. }
  329. }
  330. if ($this->throwVariableExceptions) {
  331. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  332. } else {
  333. return '';
  334. }
  335. }
  336. /**
  337. * Retrieve the partial corresponding to the requested tag name.
  338. *
  339. * Silently fails (i.e. returns '') when the requested partial is not found.
  340. *
  341. * @access protected
  342. * @param string $tag_name
  343. * @throws MustacheException Unknown partial name.
  344. * @return string
  345. */
  346. protected function getPartial($tag_name) {
  347. if (is_array($this->partials) && isset($this->partials[$tag_name])) {
  348. return $this->partials[$tag_name];
  349. }
  350. if ($this->throwPartialExceptions) {
  351. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  352. } else {
  353. return '';
  354. }
  355. }
  356. /**
  357. * Check whether the given $var should be iterated (i.e. in a section context).
  358. *
  359. * @access protected
  360. * @param mixed $var
  361. * @return bool
  362. */
  363. protected function varIsIterable($var) {
  364. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  365. }
  366. /**
  367. * Prepare a string to be used in a regular expression.
  368. *
  369. * @access protected
  370. * @param string $str
  371. * @return string
  372. */
  373. protected function prepareRegEx($str) {
  374. $replace = array(
  375. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  376. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  377. '{' => '\{', '}' => '\}', ',' => '\,'
  378. );
  379. return strtr($str, $replace);
  380. }
  381. }
  382. /**
  383. * MustacheException class.
  384. *
  385. * @extends Exception
  386. */
  387. class MustacheException extends Exception {
  388. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  389. // in the current context.
  390. const UNKNOWN_VARIABLE = 0;
  391. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  392. const UNCLOSED_SECTION = 1;
  393. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  394. // without a corresponding {{#section}}.
  395. const UNEXPECTED_CLOSE_SECTION = 2;
  396. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  397. // with no associated partial.
  398. const UNKNOWN_PARTIAL = 3;
  399. }