Mustache.php 10 KB

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