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