Mustache.php 11 KB

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