Mustache.php 8.8 KB

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