variable resolution - bobthecow/mustache.php GitHub Wiki
Mustache employs a context stack for variable resolution. Each tag (variable or section) is looked up in this stack, starting with the most recent section scope and ending with the global template scope.
Given the following context:
<?php
[
'foo' => [
'bar' => [
'baz' => 'qux',
],
],
];and this template:
{{# foo }}{{# bar }}{{ baz }}{{/ bar }}{{/ foo }}Mustache will render "qux".
This is because each section pushes a new scope onto the context stack. Inside {{#foo}}, the section scope is:
<?php
[
'bar' => [
'baz' => 'qux',
],
];Similarly, inside {{#bar}} the section scope is:
<?php
[
'baz' => 'qux',
];Which means that the variable {{baz}} is resolved in the current section scope. If a value is not found in the current
scope, each higher scope is checked until a value is found.
For example, when resolving {{#foo}}{{bar}}{{/foo}}, Mustache follows this pattern:
- Find
barin the{{#foo}}section context:- If
foois an associative array:- If
baris a valid array element, return$foo['bar'].
- If
- If
foois an object:- If
baris a valid method, return$foo->bar(). - If
baris a valid property, return$foo->bar. - If
fooimplements ArrayAccess:- If
barisset, return$foo['bar'].
- If
- If
- If
- If
barhas not been found, check the next higher scope forbar— continuing until it reaches the global scope. - If no scope contains a valid value for
bar, return an empty string.
Note that the resolution for dot notation differs somewhat. When resolving {{foo.bar.baz}}, Mustache follows this pattern:
- Using the method described above, find
fooanywhere in the context stack. - Find
barin the elements, properties and methods offoo:- If
foois an associative array:- If
baris a valid array element, return$foo['bar'].
- If
- If
foois an object:- If
baris a valid method, return$foo->bar(). - If
baris a valid property, return$foo->bar. - If
fooimplements ArrayAccess:- If
barisset, return$foo['bar'].
- If
- If
- If
- Following the same pattern, find
bazin the elements, properties and methods ofbar. - If at any point in this process a valid element, method or property is not found, return an empty string.