Mustache.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. /**
  18. * Should this Mustache throw exceptions when it finds unexpected tags?
  19. *
  20. * @see self::_throwsException()
  21. */
  22. protected $_throwsExceptions = array(
  23. MustacheException::UNKNOWN_VARIABLE => false,
  24. MustacheException::UNCLOSED_SECTION => true,
  25. MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  26. MustacheException::UNKNOWN_PARTIAL => false,
  27. MustacheException::UNKNOWN_PRAGMA => true,
  28. );
  29. // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8.
  30. protected $_charset = 'UTF-8';
  31. /**
  32. * Pragmas are macro-like directives that, when invoked, change the behavior or
  33. * syntax of Mustache.
  34. *
  35. * They should be considered extremely experimental. Most likely their implementation
  36. * will change in the future.
  37. */
  38. /**
  39. * The {{%DOT-NOTATION}} pragma allows context traversal via dots. Given the following context:
  40. *
  41. * $context = array('foo' => array('bar' => array('baz' => 'qux')));
  42. *
  43. * One could access nested properties using dot notation:
  44. *
  45. * {{%DOT-NOTATION}}{{foo.bar.baz}}
  46. *
  47. * Which would render as `qux`.
  48. */
  49. const PRAGMA_DOT_NOTATION = 'DOT-NOTATION';
  50. /**
  51. * The {{%IMPLICIT-ITERATOR}} pragma allows access to non-associative array data in an
  52. * iterable section:
  53. *
  54. * $context = array('items' => array('foo', 'bar', 'baz'));
  55. *
  56. * With this template:
  57. *
  58. * {{%IMPLICIT-ITERATOR}}{{#items}}{{.}}{{/items}}
  59. *
  60. * Would render as `foobarbaz`.
  61. *
  62. * {{%IMPLICIT-ITERATOR}} accepts an optional 'iterator' argument which allows implicit
  63. * iterator tags other than {{.}} ...
  64. *
  65. * {{%IMPLICIT-ITERATOR iterator=i}}{{#items}}{{i}}{{/items}}
  66. */
  67. const PRAGMA_IMPLICIT_ITERATOR = 'IMPLICIT-ITERATOR';
  68. /**
  69. * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}}
  70. * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be
  71. * escaped while the {{{unescaped}}} tag will be escaped.
  72. *
  73. * Pragmas apply only to the current template. Partials, even those included after the
  74. * {{%UNESCAPED}} call, will need their own pragma declaration.
  75. *
  76. * This may be useful in non-HTML Mustache situations.
  77. */
  78. const PRAGMA_UNESCAPED = 'UNESCAPED';
  79. protected $_tagRegEx;
  80. protected $_template = '';
  81. protected $_context = array();
  82. protected $_partials = array();
  83. protected $_pragmas = array();
  84. protected $_pragmasImplemented = array(
  85. self::PRAGMA_DOT_NOTATION,
  86. self::PRAGMA_IMPLICIT_ITERATOR,
  87. self::PRAGMA_UNESCAPED
  88. );
  89. protected $_localPragmas = array();
  90. /**
  91. * Mustache class constructor.
  92. *
  93. * This method accepts a $template string and a $view object. Optionally, pass an associative
  94. * array of partials as well.
  95. *
  96. * @access public
  97. * @param string $template (default: null)
  98. * @param mixed $view (default: null)
  99. * @param array $partials (default: null)
  100. * @return void
  101. */
  102. public function __construct($template = null, $view = null, $partials = null) {
  103. if ($template !== null) $this->_template = $template;
  104. if ($partials !== null) $this->_partials = $partials;
  105. if ($view !== null) $this->_context = array($view);
  106. }
  107. /**
  108. * Mustache class clone method.
  109. *
  110. * A cloned Mustache instance should have pragmas, delimeters and root context
  111. * reset to default values.
  112. *
  113. * @access public
  114. * @return void
  115. */
  116. public function __clone() {
  117. $this->_otag = '{{';
  118. $this->_ctag = '}}';
  119. $this->_localPragmas = array();
  120. if ($keys = array_keys($this->_context)) {
  121. $last = array_pop($keys);
  122. if ($this->_context[$last] instanceof Mustache) {
  123. $this->_context[$last] =& $this;
  124. }
  125. }
  126. }
  127. /**
  128. * Render the given template and view object.
  129. *
  130. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  131. * Optionally, pass an associative array of partials as well.
  132. *
  133. * @access public
  134. * @param string $template (default: null)
  135. * @param mixed $view (default: null)
  136. * @param array $partials (default: null)
  137. * @return string Rendered Mustache template.
  138. */
  139. public function render($template = null, $view = null, $partials = null) {
  140. if ($template === null) $template = $this->_template;
  141. if ($partials !== null) $this->_partials = $partials;
  142. if ($view) {
  143. $this->_context = array($view);
  144. } else if (empty($this->_context)) {
  145. $this->_context = array($this);
  146. }
  147. $template = $this->_renderPragmas($template);
  148. return $this->_renderTemplate($template, $this->_context);
  149. }
  150. /**
  151. * Wrap the render() function for string conversion.
  152. *
  153. * @access public
  154. * @return string
  155. */
  156. public function __toString() {
  157. // PHP doesn't like exceptions in __toString.
  158. // catch any exceptions and convert them to strings.
  159. try {
  160. $result = $this->render();
  161. return $result;
  162. } catch (Exception $e) {
  163. return "Error rendering mustache: " . $e->getMessage();
  164. }
  165. }
  166. /**
  167. * Internal render function, used for recursive calls.
  168. *
  169. * @access protected
  170. * @param string $template
  171. * @return string Rendered Mustache template.
  172. */
  173. protected function _renderTemplate($template) {
  174. $template = $this->_renderSections($template);
  175. return $this->_renderTags($template);
  176. }
  177. /**
  178. * Render boolean, enumerable and inverted sections.
  179. *
  180. * @access protected
  181. * @param string $template
  182. * @return string
  183. */
  184. protected function _renderSections($template) {
  185. while ($section_data = $this->_findSection($template)) {
  186. list($section, $offset, $type, $tag_name, $content) = $section_data;
  187. $replace = '';
  188. $val = $this->_getVariable($tag_name);
  189. switch($type) {
  190. // inverted section
  191. case '^':
  192. if (empty($val)) {
  193. $replace .= $content;
  194. }
  195. break;
  196. // regular section
  197. case '#':
  198. if ($this->_varIsIterable($val)) {
  199. if ($this->_hasPragma(self::PRAGMA_IMPLICIT_ITERATOR)) {
  200. if ($opt = $this->_getPragmaOptions(self::PRAGMA_IMPLICIT_ITERATOR)) {
  201. $iterator = $opt['iterator'];
  202. } else {
  203. $iterator = '.';
  204. }
  205. } else {
  206. $iterator = false;
  207. }
  208. foreach ($val as $local_context) {
  209. if ($iterator) {
  210. $iterator_context = array($iterator => $local_context);
  211. $this->_pushContext($iterator_context);
  212. } else {
  213. $this->_pushContext($local_context);
  214. }
  215. $replace .= $this->_renderTemplate($content);
  216. $this->_popContext();
  217. }
  218. } else if ($val) {
  219. if (is_array($val) || is_object($val)) {
  220. $this->_pushContext($val);
  221. $replace .= $this->_renderTemplate($content);
  222. $this->_popContext();
  223. } else {
  224. $replace .= $content;
  225. }
  226. }
  227. break;
  228. }
  229. $template = substr_replace($template, $replace, $offset, strlen($section));
  230. }
  231. return $template;
  232. }
  233. const SECTION_TYPES = '^#/';
  234. protected function _prepareSectionRegEx($otag, $ctag) {
  235. return sprintf(
  236. '/(?:(?<=\\n)[ \\t]*)?%s(?<type>[%s])(?<tag_name>.+?)%s\\n?/s',
  237. preg_quote($otag, '/'),
  238. preg_quote(self::SECTION_TYPES, '/'),
  239. preg_quote($ctag, '/')
  240. );
  241. }
  242. /**
  243. * Extract a section from $template.
  244. *
  245. * This is a helper function to find sections needed by _renderSections.
  246. *
  247. * @access protected
  248. * @param string $template
  249. * @return array $section, $offset, $type, $tag_name and $content
  250. */
  251. protected function _findSection($template) {
  252. $regex = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
  253. $section_start = null;
  254. $section_type = null;
  255. $content_start = null;
  256. $search_offset = 0;
  257. $section_stack = array();
  258. $matches = array();
  259. while (preg_match($regex, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
  260. $match = $matches[0][0];
  261. $offset = $matches[0][1];
  262. $type = $matches['type'][0];
  263. $tag_name = trim($matches['tag_name'][0]);
  264. $search_offset = $offset + strlen($match);
  265. switch ($type) {
  266. case '^':
  267. case '#':
  268. if (empty($section_stack)) {
  269. $section_start = $offset;
  270. $section_type = $type;
  271. $content_start = $search_offset;
  272. }
  273. array_push($section_stack, $tag_name);
  274. break;
  275. case '/':
  276. if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
  277. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  278. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  279. }
  280. }
  281. if (empty($section_stack)) {
  282. $section = substr($template, $section_start, $search_offset - $section_start);
  283. $content = substr($template, $content_start, $offset - $content_start);
  284. return array($section, $section_start, $section_type, $tag_name, $content);
  285. }
  286. break;
  287. }
  288. }
  289. if (!empty($section_stack)) {
  290. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  291. throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
  292. }
  293. }
  294. }
  295. protected function _preparePragmaRegEx($otag, $ctag) {
  296. return sprintf(
  297. '/%s%%\\s*(?<pragma_name>[\\w_-]+)(?<options_string>(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s',
  298. preg_quote($otag, '/'),
  299. preg_quote($ctag, '/')
  300. );
  301. }
  302. /**
  303. * Initialize pragmas and remove all pragma tags.
  304. *
  305. * @access protected
  306. * @param string $template
  307. * @return string
  308. */
  309. protected function _renderPragmas($template) {
  310. $this->_localPragmas = $this->_pragmas;
  311. // no pragmas
  312. if (strpos($template, $this->_otag . '%') === false) {
  313. return $template;
  314. }
  315. $regex = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
  316. return preg_replace_callback($regex, array($this, '_renderPragma'), $template);
  317. }
  318. /**
  319. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  320. *
  321. * @access protected
  322. * @param mixed $matches
  323. * @return void
  324. * @throws MustacheException unknown pragma
  325. */
  326. protected function _renderPragma($matches) {
  327. $pragma = $matches[0];
  328. $pragma_name = $matches['pragma_name'];
  329. $options_string = $matches['options_string'];
  330. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  331. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  332. }
  333. $options = array();
  334. foreach (explode(' ', trim($options_string)) as $o) {
  335. if ($p = trim($o)) {
  336. $p = explode('=', trim($p));
  337. $options[$p[0]] = $p[1];
  338. }
  339. }
  340. if (empty($options)) {
  341. $this->_localPragmas[$pragma_name] = true;
  342. } else {
  343. $this->_localPragmas[$pragma_name] = $options;
  344. }
  345. return '';
  346. }
  347. /**
  348. * Check whether this Mustache has a specific pragma.
  349. *
  350. * @access protected
  351. * @param string $pragma_name
  352. * @return bool
  353. */
  354. protected function _hasPragma($pragma_name) {
  355. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  356. return true;
  357. } else {
  358. return false;
  359. }
  360. }
  361. /**
  362. * Return pragma options, if any.
  363. *
  364. * @access protected
  365. * @param string $pragma_name
  366. * @return mixed
  367. * @throws MustacheException Unknown pragma
  368. */
  369. protected function _getPragmaOptions($pragma_name) {
  370. if (!$this->_hasPragma($pragma_name)) {
  371. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  372. }
  373. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  374. }
  375. /**
  376. * Check whether this Mustache instance throws a given exception.
  377. *
  378. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  379. *
  380. * @access protected
  381. * @param mixed $exception
  382. * @return void
  383. */
  384. protected function _throwsException($exception) {
  385. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  386. }
  387. const TAG_TYPES = '#^/=!<>\\{&';
  388. protected function _prepareTagRegex($otag, $ctag) {
  389. return sprintf(
  390. '/(?:(?<=\\n)[ \\t]*)?%s(?<type>[%s]?)(?<tag_name>.+?)(?:\\1|})?%s(?:\\s*(?=\\n))?/s',
  391. preg_quote($otag, '/'),
  392. preg_quote(self::TAG_TYPES, '/'),
  393. preg_quote($ctag, '/')
  394. );
  395. }
  396. /**
  397. * Loop through and render individual Mustache tags.
  398. *
  399. * @access protected
  400. * @param string $template
  401. * @return void
  402. */
  403. protected function _renderTags($template) {
  404. if (strpos($template, $this->_otag) === false) {
  405. return $template;
  406. }
  407. $otag_orig = $this->_otag;
  408. $ctag_orig = $this->_ctag;
  409. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  410. $html = '';
  411. $matches = array();
  412. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  413. $tag = $matches[0][0];
  414. $offset = $matches[0][1];
  415. $modifier = $matches['type'][0];
  416. $tag_name = trim($matches['tag_name'][0]);
  417. $html .= substr($template, 0, $offset);
  418. $next_offset = $offset + strlen($tag);
  419. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  420. $next_offset++;
  421. }
  422. $template = substr($template, $next_offset);
  423. $html .= $this->_renderTag($modifier, $tag_name);
  424. }
  425. $this->_otag = $otag_orig;
  426. $this->_ctag = $ctag_orig;
  427. return $html . $template;
  428. }
  429. /**
  430. * Render the named tag, given the specified modifier.
  431. *
  432. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  433. * `{` or `&` (don't escape output), or none (render escaped output).
  434. *
  435. * @access protected
  436. * @param string $modifier
  437. * @param string $tag_name
  438. * @throws MustacheException Unmatched section tag encountered.
  439. * @return string
  440. */
  441. protected function _renderTag($modifier, $tag_name) {
  442. switch ($modifier) {
  443. case '#':
  444. case '^':
  445. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  446. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  447. } else {
  448. return '';
  449. }
  450. break;
  451. case '/':
  452. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  453. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  454. } else {
  455. return '';
  456. }
  457. break;
  458. case '=':
  459. return $this->_changeDelimiter($tag_name);
  460. break;
  461. case '!':
  462. return $this->_renderComment($tag_name);
  463. break;
  464. case '>':
  465. case '<':
  466. return $this->_renderPartial($tag_name);
  467. break;
  468. case '{':
  469. // strip the trailing } ...
  470. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  471. $tag_name = substr($tag_name, 0, -1);
  472. }
  473. case '&':
  474. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  475. return $this->_renderEscaped($tag_name);
  476. } else {
  477. return $this->_renderUnescaped($tag_name);
  478. }
  479. break;
  480. }
  481. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  482. return $this->_renderUnescaped($modifier . $tag_name);
  483. } else {
  484. return $this->_renderEscaped($modifier . $tag_name);
  485. }
  486. }
  487. /**
  488. * Escape and return the requested tag.
  489. *
  490. * @access protected
  491. * @param string $tag_name
  492. * @return string
  493. */
  494. protected function _renderEscaped($tag_name) {
  495. return htmlentities($this->_getVariable($tag_name), ENT_COMPAT, $this->_charset);
  496. }
  497. /**
  498. * Render a comment (i.e. return an empty string).
  499. *
  500. * @access protected
  501. * @param string $tag_name
  502. * @return string
  503. */
  504. protected function _renderComment($tag_name) {
  505. return '';
  506. }
  507. /**
  508. * Return the requested tag unescaped.
  509. *
  510. * @access protected
  511. * @param string $tag_name
  512. * @return string
  513. */
  514. protected function _renderUnescaped($tag_name) {
  515. return $this->_getVariable($tag_name);
  516. }
  517. /**
  518. * Render the requested partial.
  519. *
  520. * @access protected
  521. * @param string $tag_name
  522. * @return string
  523. */
  524. protected function _renderPartial($tag_name) {
  525. $view = clone($this);
  526. return $view->render($this->_getPartial($tag_name));
  527. }
  528. /**
  529. * Change the Mustache tag delimiter. This method also replaces this object's current
  530. * tag RegEx with one using the new delimiters.
  531. *
  532. * @access protected
  533. * @param string $tag_name
  534. * @return string
  535. */
  536. protected function _changeDelimiter($tag_name) {
  537. list($otag, $ctag) = explode(' ', $tag_name);
  538. $this->_otag = $otag;
  539. $this->_ctag = $ctag;
  540. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  541. return '';
  542. }
  543. /**
  544. * Push a local context onto the stack.
  545. *
  546. * @access protected
  547. * @param array &$local_context
  548. * @return void
  549. */
  550. protected function _pushContext(&$local_context) {
  551. $new = array();
  552. $new[] =& $local_context;
  553. foreach (array_keys($this->_context) as $key) {
  554. $new[] =& $this->_context[$key];
  555. }
  556. $this->_context = $new;
  557. }
  558. /**
  559. * Remove the latest context from the stack.
  560. *
  561. * @access protected
  562. * @return void
  563. */
  564. protected function _popContext() {
  565. $new = array();
  566. $keys = array_keys($this->_context);
  567. array_shift($keys);
  568. foreach ($keys as $key) {
  569. $new[] =& $this->_context[$key];
  570. }
  571. $this->_context = $new;
  572. }
  573. /**
  574. * Get a variable from the context array.
  575. *
  576. * If the view is an array, returns the value with array key $tag_name.
  577. * If the view is an object, this will check for a public member variable
  578. * named $tag_name. If none is available, this method will execute and return
  579. * any class method named $tag_name. Failing all of the above, this method will
  580. * return an empty string.
  581. *
  582. * @access protected
  583. * @param string $tag_name
  584. * @throws MustacheException Unknown variable name.
  585. * @return string
  586. */
  587. protected function _getVariable($tag_name) {
  588. if ($this->_hasPragma(self::PRAGMA_DOT_NOTATION) && $tag_name != '.') {
  589. $chunks = explode('.', $tag_name);
  590. $first = array_shift($chunks);
  591. $ret = $this->_findVariableInContext($first, $this->_context);
  592. while ($next = array_shift($chunks)) {
  593. // Slice off a chunk of context for dot notation traversal.
  594. $c = array($ret);
  595. $ret = $this->_findVariableInContext($next, $c);
  596. }
  597. return $ret;
  598. } else {
  599. return $this->_findVariableInContext($tag_name, $this->_context);
  600. }
  601. }
  602. /**
  603. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  604. * variable traversal for dot notation.
  605. *
  606. * @access protected
  607. * @param string $tag_name
  608. * @param array $context
  609. * @throws MustacheException Unknown variable name.
  610. * @return string
  611. */
  612. protected function _findVariableInContext($tag_name, $context) {
  613. foreach ($context as $view) {
  614. if (is_object($view)) {
  615. if (method_exists($view, $tag_name)) {
  616. return $view->$tag_name();
  617. } else if (isset($view->$tag_name)) {
  618. return $view->$tag_name;
  619. }
  620. } else if (array_key_exists($tag_name, $view)) {
  621. return $view[$tag_name];
  622. }
  623. }
  624. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  625. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  626. } else {
  627. return '';
  628. }
  629. }
  630. /**
  631. * Retrieve the partial corresponding to the requested tag name.
  632. *
  633. * Silently fails (i.e. returns '') when the requested partial is not found.
  634. *
  635. * @access protected
  636. * @param string $tag_name
  637. * @throws MustacheException Unknown partial name.
  638. * @return string
  639. */
  640. protected function _getPartial($tag_name) {
  641. if (is_array($this->_partials) && isset($this->_partials[$tag_name])) {
  642. return $this->_partials[$tag_name];
  643. }
  644. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  645. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  646. } else {
  647. return '';
  648. }
  649. }
  650. /**
  651. * Check whether the given $var should be iterated (i.e. in a section context).
  652. *
  653. * @access protected
  654. * @param mixed $var
  655. * @return bool
  656. */
  657. protected function _varIsIterable($var) {
  658. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  659. }
  660. }
  661. /**
  662. * MustacheException class.
  663. *
  664. * @extends Exception
  665. */
  666. class MustacheException extends Exception {
  667. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  668. // in the current context.
  669. const UNKNOWN_VARIABLE = 0;
  670. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  671. const UNCLOSED_SECTION = 1;
  672. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  673. // without a corresponding {{#section}} or {{^section}}.
  674. const UNEXPECTED_CLOSE_SECTION = 2;
  675. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  676. // with no associated partial.
  677. const UNKNOWN_PARTIAL = 3;
  678. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  679. // which can't be handled by this Mustache instance.
  680. const UNKNOWN_PRAGMA = 4;
  681. }