Mustache.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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;
  20. protected $partials;
  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. $this->template = $template;
  35. $this->partials = $partials;
  36. if ($view) {
  37. $this->context = array($view);
  38. }
  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. return $this->changeDelimiter($tag_name, $context);
  152. break;
  153. case '!':
  154. return $this->renderComment($tag_name, $context);
  155. break;
  156. case '>':
  157. return $this->renderPartial($tag_name, $context);
  158. break;
  159. case '{':
  160. case '&':
  161. return $this->renderUnescaped($tag_name, $context);
  162. break;
  163. case '':
  164. default:
  165. return $this->renderEscaped($tag_name, $context);
  166. break;
  167. }
  168. }
  169. /**
  170. * Escape and return the requested tag.
  171. *
  172. * @access protected
  173. * @param string $tag_name
  174. * @param array $context
  175. * @return string
  176. */
  177. protected function renderEscaped($tag_name, &$context) {
  178. return htmlentities($this->getVariable($tag_name, $context));
  179. }
  180. /**
  181. * Render a comment (i.e. return an empty string).
  182. *
  183. * @access protected
  184. * @param string $tag_name
  185. * @param array $context
  186. * @return string
  187. */
  188. protected function renderComment($tag_name, &$context) {
  189. return '';
  190. }
  191. /**
  192. * Return the requested tag unescaped.
  193. *
  194. * @access protected
  195. * @param string $tag_name
  196. * @param array $context
  197. * @return string
  198. */
  199. protected function renderUnescaped($tag_name, &$context) {
  200. return $this->getVariable($tag_name, $context);
  201. }
  202. /**
  203. * Render the requested partial.
  204. *
  205. * @access protected
  206. * @param string $tag_name
  207. * @param array $context
  208. * @return string
  209. */
  210. protected function renderPartial($tag_name, &$context) {
  211. $view = new self($this->getPartial($tag_name), $context, $this->partials);
  212. $view->otag = $this->otag;
  213. $view->ctag = $this->ctag;
  214. return $view->render();
  215. }
  216. /**
  217. * Change the Mustache tag delimiter. This method also replaces this object's current
  218. * tag RegEx with one using the new delimiters.
  219. *
  220. * @access protected
  221. * @param string $tag_name
  222. * @param array $context
  223. * @return string
  224. */
  225. protected function changeDelimiter($tag_name, &$context) {
  226. $tags = explode(' ', $tag_name);
  227. $this->otag = $tags[0];
  228. $this->ctag = $tags[1];
  229. $otag = $this->prepareRegEx($this->otag);
  230. $ctag = $this->prepareRegEx($this->ctag);
  231. $this->tagRegEx = '/' . $otag . "(=|!|>|\\{|%)?([^\/#]+?)\\1?" . $ctag . "+/";
  232. return '';
  233. }
  234. /**
  235. * Prepare a new context reference array.
  236. *
  237. * This is used to create context arrays for iterable blocks.
  238. *
  239. * @access protected
  240. * @param array $context
  241. * @param mixed $local_context
  242. * @return void
  243. */
  244. protected function getContext(&$context, &$local_context) {
  245. $ret = array();
  246. $ret[] =& $local_context;
  247. foreach ($context as $view) {
  248. $ret[] =& $view;
  249. }
  250. return $ret;
  251. }
  252. /**
  253. * Get a variable from the context array.
  254. *
  255. * If the view is an array, returns the value with array key $tag_name.
  256. * If the view is an object, this will check for a public member variable
  257. * named $tag_name. If none is available, this method will execute and return
  258. * any class method named $tag_name. Failing all of the above, this method will
  259. * return an empty string.
  260. *
  261. * @access protected
  262. * @param string $tag_name
  263. * @param array $context
  264. * @return string
  265. */
  266. protected function getVariable($tag_name, &$context) {
  267. foreach ($context as $view) {
  268. if (is_object($view)) {
  269. if (isset($view->$tag_name)) {
  270. return $view->$tag_name;
  271. } else if (method_exists($view, $tag_name)) {
  272. return $view->$tag_name();
  273. }
  274. } else if (isset($view[$tag_name])) {
  275. return $view[$tag_name];
  276. }
  277. }
  278. return '';
  279. }
  280. /**
  281. * Retrieve the partial corresponding to the requested tag name.
  282. *
  283. * Silently fails (i.e. returns '') when the requested partial is not found.
  284. *
  285. * @access protected
  286. * @param string $tag_name
  287. * @return string
  288. */
  289. protected function getPartial($tag_name) {
  290. if (is_array($this->partials) && isset($this->partials[$tag_name])) {
  291. return $this->partials[$tag_name];
  292. }
  293. return '';
  294. }
  295. /**
  296. * Prepare a string to be used in a regular expression.
  297. *
  298. * @access protected
  299. * @param string $str
  300. * @return string
  301. */
  302. protected function prepareRegEx($str) {
  303. $replace = array(
  304. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  305. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  306. '{' => '\{', '}' => '\}', ',' => '\,'
  307. );
  308. return strtr($str, $replace);
  309. }
  310. }