Variable Resolution - bobthecow/mustache.php GitHub Wiki
Variable Resolution
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
array(
'foo' => array(
'bar' => array(
'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
array(
'bar' => array(
'baz' => 'qux',
),
);
Similarly, inside {{#bar}}
the section scope is:
<?php
array(
'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
bar
in the{{#foo}}
section context:- If
foo
is an associative array:- If
bar
is a valid array element, return$foo['bar']
.
- If
- If
foo
is an object:- If
bar
is a valid method, return$foo->bar()
. - If
bar
is a valid property, return$foo->bar
. - If
foo
implements ArrayAccess:- If
bar
isset, return$foo['bar']
.
- If
- If
- If
- If
bar
has 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
foo
anywhere in the context stack. - Find
bar
in the elements, properties and methods offoo
:- If
foo
is an associative array:- If
bar
is a valid array element, return$foo['bar']
.
- If
- If
foo
is an object:- If
bar
is a valid method, return$foo->bar()
. - If
bar
is a valid property, return$foo->bar
. - If
foo
implements ArrayAccess:- If
bar
isset, return$foo['bar']
.
- If
- If
- If
- Following the same pattern, find
baz
in 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.