Mustache.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. /**
  239. * Prepare a section RegEx string for the given opening/closing tags.
  240. *
  241. * @access protected
  242. * @param string $otag
  243. * @param string $ctag
  244. * @return string
  245. */
  246. protected function _prepareSectionRegEx($otag, $ctag) {
  247. return sprintf(
  248. '/(?:(?<=\\n)[ \\t]*)?%s(?P<type>[%s])(?P<tag_name>.+?)%s\\n?/s',
  249. preg_quote($otag, '/'),
  250. self::SECTION_TYPES,
  251. preg_quote($ctag, '/')
  252. );
  253. }
  254. /**
  255. * Extract a section from $template.
  256. *
  257. * This is a helper function to find sections needed by _renderSections.
  258. *
  259. * @access protected
  260. * @param string $template
  261. * @return array $section, $offset, $type, $tag_name and $content
  262. */
  263. protected function _findSection($template) {
  264. $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
  265. $section_start = null;
  266. $section_type = null;
  267. $content_start = null;
  268. $search_offset = 0;
  269. $section_stack = array();
  270. $matches = array();
  271. while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
  272. $match = $matches[0][0];
  273. $offset = $matches[0][1];
  274. $type = $matches['type'][0];
  275. $tag_name = trim($matches['tag_name'][0]);
  276. $search_offset = $offset + strlen($match);
  277. switch ($type) {
  278. case '^':
  279. case '#':
  280. if (empty($section_stack)) {
  281. $section_start = $offset;
  282. $section_type = $type;
  283. $content_start = $search_offset;
  284. }
  285. array_push($section_stack, $tag_name);
  286. break;
  287. case '/':
  288. if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
  289. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  290. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  291. }
  292. }
  293. if (empty($section_stack)) {
  294. $section = substr($template, $section_start, $search_offset - $section_start);
  295. $content = substr($template, $content_start, $offset - $content_start);
  296. return array($section, $section_start, $section_type, $tag_name, $content);
  297. }
  298. break;
  299. }
  300. }
  301. if (!empty($section_stack)) {
  302. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  303. throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
  304. }
  305. }
  306. }
  307. /**
  308. * Prepare a pragma RegEx for the given opening/closing tags.
  309. *
  310. * @access protected
  311. * @param string $otag
  312. * @param string $ctag
  313. * @return string
  314. */
  315. protected function _preparePragmaRegEx($otag, $ctag) {
  316. return sprintf(
  317. '/%s%%\\s*(?P<pragma_name>[\\w_-]+)(?P<options_string>(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s',
  318. preg_quote($otag, '/'),
  319. preg_quote($ctag, '/')
  320. );
  321. }
  322. /**
  323. * Initialize pragmas and remove all pragma tags.
  324. *
  325. * @access protected
  326. * @param string $template
  327. * @return string
  328. */
  329. protected function _renderPragmas($template) {
  330. $this->_localPragmas = $this->_pragmas;
  331. // no pragmas
  332. if (strpos($template, $this->_otag . '%') === false) {
  333. return $template;
  334. }
  335. $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
  336. return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
  337. }
  338. /**
  339. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  340. *
  341. * @access protected
  342. * @param mixed $matches
  343. * @return void
  344. * @throws MustacheException unknown pragma
  345. */
  346. protected function _renderPragma($matches) {
  347. $pragma = $matches[0];
  348. $pragma_name = $matches['pragma_name'];
  349. $options_string = $matches['options_string'];
  350. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  351. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  352. }
  353. $options = array();
  354. foreach (explode(' ', trim($options_string)) as $o) {
  355. if ($p = trim($o)) {
  356. $p = explode('=', $p);
  357. $options[$p[0]] = $p[1];
  358. }
  359. }
  360. if (empty($options)) {
  361. $this->_localPragmas[$pragma_name] = true;
  362. } else {
  363. $this->_localPragmas[$pragma_name] = $options;
  364. }
  365. return '';
  366. }
  367. /**
  368. * Check whether this Mustache has a specific pragma.
  369. *
  370. * @access protected
  371. * @param string $pragma_name
  372. * @return bool
  373. */
  374. protected function _hasPragma($pragma_name) {
  375. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  376. return true;
  377. } else {
  378. return false;
  379. }
  380. }
  381. /**
  382. * Return pragma options, if any.
  383. *
  384. * @access protected
  385. * @param string $pragma_name
  386. * @return mixed
  387. * @throws MustacheException Unknown pragma
  388. */
  389. protected function _getPragmaOptions($pragma_name) {
  390. if (!$this->_hasPragma($pragma_name)) {
  391. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  392. }
  393. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  394. }
  395. /**
  396. * Check whether this Mustache instance throws a given exception.
  397. *
  398. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  399. *
  400. * @access protected
  401. * @param mixed $exception
  402. * @return void
  403. */
  404. protected function _throwsException($exception) {
  405. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  406. }
  407. /**
  408. * Prepare a tag RegEx for the given opening/closing tags.
  409. *
  410. * @access protected
  411. * @param string $otag
  412. * @param string $ctag
  413. * @return string
  414. */
  415. protected function _prepareTagRegEx($otag, $ctag) {
  416. return sprintf(
  417. '/(?P<whitespace>(?<=\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?:\\s*(?=\\n))?/s',
  418. preg_quote($otag, '/'),
  419. self::TAG_TYPES,
  420. preg_quote($ctag, '/')
  421. );
  422. }
  423. /**
  424. * Loop through and render individual Mustache tags.
  425. *
  426. * @access protected
  427. * @param string $template
  428. * @return void
  429. */
  430. protected function _renderTags($template) {
  431. if (strpos($template, $this->_otag) === false) {
  432. return $template;
  433. }
  434. $otag_orig = $this->_otag;
  435. $ctag_orig = $this->_ctag;
  436. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  437. $html = '';
  438. $matches = array();
  439. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  440. $tag = $matches[0][0];
  441. $offset = $matches[0][1];
  442. $modifier = $matches['type'][0];
  443. $tag_name = trim($matches['tag_name'][0]);
  444. if (isset($matches['whitespace']) && $matches['whitespace'][1] > -1) {
  445. $whitespace = $matches['whitespace'][0];
  446. } else {
  447. $whitespace = null;
  448. }
  449. $html .= substr($template, 0, $offset);
  450. $next_offset = $offset + strlen($tag);
  451. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  452. $next_offset++;
  453. }
  454. $template = substr($template, $next_offset);
  455. $html .= $this->_renderTag($modifier, $tag_name, $whitespace);
  456. }
  457. $this->_otag = $otag_orig;
  458. $this->_ctag = $ctag_orig;
  459. return $html . $template;
  460. }
  461. /**
  462. * Render the named tag, given the specified modifier.
  463. *
  464. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  465. * `{` or `&` (don't escape output), or none (render escaped output).
  466. *
  467. * @access protected
  468. * @param string $modifier
  469. * @param string $tag_name
  470. * @throws MustacheException Unmatched section tag encountered.
  471. * @return string
  472. */
  473. protected function _renderTag($modifier, $tag_name, $whitespace) {
  474. switch ($modifier) {
  475. case '=':
  476. return $this->_changeDelimiter($tag_name);
  477. break;
  478. case '!':
  479. return $this->_renderComment($tag_name);
  480. break;
  481. case '>':
  482. case '<':
  483. return $this->_renderPartial($tag_name, $whitespace);
  484. break;
  485. case '{':
  486. // strip the trailing } ...
  487. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  488. $tag_name = substr($tag_name, 0, -1);
  489. }
  490. case '&':
  491. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  492. return $this->_renderEscaped($tag_name);
  493. } else {
  494. return $this->_renderUnescaped($tag_name);
  495. }
  496. break;
  497. case '#':
  498. case '^':
  499. case '/':
  500. // remove any leftovers from _renderSections
  501. return '';
  502. break;
  503. }
  504. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  505. return $this->_renderUnescaped($modifier . $tag_name);
  506. } else {
  507. return $this->_renderEscaped($modifier . $tag_name);
  508. }
  509. }
  510. /**
  511. * Escape and return the requested tag.
  512. *
  513. * @access protected
  514. * @param string $tag_name
  515. * @return string
  516. */
  517. protected function _renderEscaped($tag_name) {
  518. return htmlentities($this->_getVariable($tag_name), ENT_COMPAT, $this->_charset);
  519. }
  520. /**
  521. * Render a comment (i.e. return an empty string).
  522. *
  523. * @access protected
  524. * @param string $tag_name
  525. * @return string
  526. */
  527. protected function _renderComment($tag_name) {
  528. return '';
  529. }
  530. /**
  531. * Return the requested tag unescaped.
  532. *
  533. * @access protected
  534. * @param string $tag_name
  535. * @return string
  536. */
  537. protected function _renderUnescaped($tag_name) {
  538. return $this->_getVariable($tag_name);
  539. }
  540. /**
  541. * Render the requested partial.
  542. *
  543. * @access protected
  544. * @param string $tag_name
  545. * @return string
  546. */
  547. protected function _renderPartial($tag_name, $whitespace = '') {
  548. $view = clone($this);
  549. $partial = $whitespace . preg_replace('/\n(?!$)/s', "\n" . $whitespace, $this->_getPartial($tag_name));
  550. return $view->render($partial);
  551. }
  552. /**
  553. * Change the Mustache tag delimiter. This method also replaces this object's current
  554. * tag RegEx with one using the new delimiters.
  555. *
  556. * @access protected
  557. * @param string $tag_name
  558. * @return string
  559. */
  560. protected function _changeDelimiter($tag_name) {
  561. list($otag, $ctag) = explode(' ', $tag_name);
  562. $this->_otag = $otag;
  563. $this->_ctag = $ctag;
  564. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  565. return '';
  566. }
  567. /**
  568. * Push a local context onto the stack.
  569. *
  570. * @access protected
  571. * @param array &$local_context
  572. * @return void
  573. */
  574. protected function _pushContext(&$local_context) {
  575. $new = array();
  576. $new[] =& $local_context;
  577. foreach (array_keys($this->_context) as $key) {
  578. $new[] =& $this->_context[$key];
  579. }
  580. $this->_context = $new;
  581. }
  582. /**
  583. * Remove the latest context from the stack.
  584. *
  585. * @access protected
  586. * @return void
  587. */
  588. protected function _popContext() {
  589. $new = array();
  590. $keys = array_keys($this->_context);
  591. array_shift($keys);
  592. foreach ($keys as $key) {
  593. $new[] =& $this->_context[$key];
  594. }
  595. $this->_context = $new;
  596. }
  597. /**
  598. * Get a variable from the context array.
  599. *
  600. * If the view is an array, returns the value with array key $tag_name.
  601. * If the view is an object, this will check for a public member variable
  602. * named $tag_name. If none is available, this method will execute and return
  603. * any class method named $tag_name. Failing all of the above, this method will
  604. * return an empty string.
  605. *
  606. * @access protected
  607. * @param string $tag_name
  608. * @throws MustacheException Unknown variable name.
  609. * @return string
  610. */
  611. protected function _getVariable($tag_name) {
  612. if ($tag_name != '.' && strpos($tag_name, '.') !== false && $this->_hasPragma(self::PRAGMA_DOT_NOTATION)) {
  613. $chunks = explode('.', $tag_name);
  614. $first = array_shift($chunks);
  615. $ret = $this->_findVariableInContext($first, $this->_context);
  616. while ($next = array_shift($chunks)) {
  617. // Slice off a chunk of context for dot notation traversal.
  618. $c = array($ret);
  619. $ret = $this->_findVariableInContext($next, $c);
  620. }
  621. return $ret;
  622. } else {
  623. return $this->_findVariableInContext($tag_name, $this->_context);
  624. }
  625. }
  626. /**
  627. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  628. * variable traversal for dot notation.
  629. *
  630. * @access protected
  631. * @param string $tag_name
  632. * @param array $context
  633. * @throws MustacheException Unknown variable name.
  634. * @return string
  635. */
  636. protected function _findVariableInContext($tag_name, $context) {
  637. foreach ($context as $view) {
  638. if (is_object($view)) {
  639. if (method_exists($view, $tag_name)) {
  640. return $view->$tag_name();
  641. } else if (isset($view->$tag_name)) {
  642. return $view->$tag_name;
  643. }
  644. } else if (array_key_exists($tag_name, $view)) {
  645. return $view[$tag_name];
  646. }
  647. }
  648. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  649. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  650. } else {
  651. return '';
  652. }
  653. }
  654. /**
  655. * Retrieve the partial corresponding to the requested tag name.
  656. *
  657. * Silently fails (i.e. returns '') when the requested partial is not found.
  658. *
  659. * @access protected
  660. * @param string $tag_name
  661. * @throws MustacheException Unknown partial name.
  662. * @return string
  663. */
  664. protected function _getPartial($tag_name) {
  665. if (is_array($this->_partials) && isset($this->_partials[$tag_name])) {
  666. return $this->_partials[$tag_name];
  667. }
  668. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  669. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  670. } else {
  671. return '';
  672. }
  673. }
  674. /**
  675. * Check whether the given $var should be iterated (i.e. in a section context).
  676. *
  677. * @access protected
  678. * @param mixed $var
  679. * @return bool
  680. */
  681. protected function _varIsIterable($var) {
  682. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  683. }
  684. }
  685. /**
  686. * MustacheException class.
  687. *
  688. * @extends Exception
  689. */
  690. class MustacheException extends Exception {
  691. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  692. // in the current context.
  693. const UNKNOWN_VARIABLE = 0;
  694. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  695. const UNCLOSED_SECTION = 1;
  696. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  697. // without a corresponding {{#section}} or {{^section}}.
  698. const UNEXPECTED_CLOSE_SECTION = 2;
  699. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  700. // with no associated partial.
  701. const UNKNOWN_PARTIAL = 3;
  702. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  703. // which can't be handled by this Mustache instance.
  704. const UNKNOWN_PRAGMA = 4;
  705. }