Mustache.php 11 KB

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