Mustache.php 10 KB

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