|
| 1 | +<?php |
| 2 | + |
| 3 | +$tmpl = <<<EOF |
| 4 | +<div class="post"> |
| 5 | + <h1>By {{fullName author}}</h1> |
| 6 | + <div class="body">{{body}}</div> |
| 7 | +
|
| 8 | + <h1>Comments</h1> |
| 9 | +
|
| 10 | + {{#each comments}} |
| 11 | + <h2>By {{fullName author}}</h2> |
| 12 | + <div class="body">{{body}}</div> |
| 13 | + {{/each}} |
| 14 | +</div> |
| 15 | +EOF; |
| 16 | + |
| 17 | +$data = array( |
| 18 | + 'author' => array('firstName' => 'Alan', 'lastName' => 'Johnson'), |
| 19 | + 'body' => 'I Love Handlebars', |
| 20 | + 'comments' => array( |
| 21 | + array( |
| 22 | + 'author' => array('firstName' => 'Yehuda', 'lastName' => 'Katz'), |
| 23 | + 'body' => 'Me too!', |
| 24 | + ), |
| 25 | + ), |
| 26 | +); |
| 27 | + |
| 28 | +class FullNameHelper { |
| 29 | + public function __invoke($person) { |
| 30 | + return $person['firstName'] . ' ' . $person['lastName']; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +class HelperLoader implements IteratorAggregate, Handlebars\Registry { |
| 35 | + private $helpers = array(); |
| 36 | + public function offsetGet($offset) { |
| 37 | + if( isset($helpers[$offset]) ) { |
| 38 | + return $helpers[$offset]; |
| 39 | + } |
| 40 | + $className = ucfirst($offset) . 'Helper'; // Transform helper name to class |
| 41 | + if( class_exists($className, true) ) { |
| 42 | + return $helpers[$offset] = new $className; |
| 43 | + } |
| 44 | + } |
| 45 | + public function offsetSet($offset, $value) { |
| 46 | + $this->helpers[$offset] = $value; |
| 47 | + } |
| 48 | + public function offsetExists($offset) { |
| 49 | + return null !== $this->offsetGet($offset); |
| 50 | + } |
| 51 | + public function offsetUnset($offset) { |
| 52 | + unset($this->helpers[$offset]); |
| 53 | + } |
| 54 | + public function getIterator() { |
| 55 | + return new ArrayIterator($this->helpers); |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +$vm = new Handlebars\VM(); |
| 60 | +$vm->setHelpers(new HelperLoader()); |
| 61 | +echo $vm->render($tmpl, $data); |
0 commit comments