TraversableMustache.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * TraversableMustache class.
  4. *
  5. * This is an implementaiton of the DOT_NOTATION pragma.
  6. *
  7. * A Mustache subclass which allows variable traversal via dots, i.e.:
  8. *
  9. * @code
  10. * class Foo extends TraversableMustache {
  11. * var $one = array(
  12. * 'two' => array(
  13. * 'three' => 'wheee!'
  14. * )
  15. * );
  16. *
  17. * protected $template = '{{one.two.three}}';
  18. * }
  19. * $foo = new Foo;
  20. * print $foo;
  21. * @endcode
  22. *
  23. * (The above code prints 'wheee!')
  24. *
  25. * @extends Mustache
  26. */
  27. class TraversableMustache extends Mustache {
  28. /**
  29. * Override default getVariable method to allow object traversal via dots.
  30. * This might be cool. Also, might be heinous.
  31. *
  32. * @access protected
  33. * @param string $tag_name
  34. * @param array &$context
  35. * @return string
  36. */
  37. protected function getVariable($tag_name, &$context) {
  38. $chunks = explode('.', $tag_name);
  39. $first = array_shift($chunks);
  40. $ret = parent::getVariable($first, $context);
  41. while ($next = array_shift($chunks)) {
  42. $c = array($ret);
  43. $ret = parent::getVariable($next, $c);
  44. }
  45. return $ret;
  46. }
  47. }