TraversableMustache.php 1.1 KB

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