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