Skip to content

Variable Resolution

Justin Hileman edited this page Dec 14, 2013 · 3 revisions

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:

  1. Find bar in the {{#foo}} section context:
    • If foo is an associative array:
      • If bar is a valid array element, return $foo['bar'].
    • 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'].
  2. If bar has not been found, check the next higher scope for bar — continuing until it reaches the global scope.
  3. 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:

  1. Using the method described above, find foo anywhere in the context stack.
  2. Find bar in the elements, properties and methods of foo:
    • If foo is an associative array:
      • If bar is a valid array element, return $foo['bar'].
    • 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'].
  3. Following the same pattern, find baz in the elements, properties and methods of bar.
  4. If at any point in this process a valid element, method or property is not found, return an empty string.