Scope and name visibility - misonou/waterpipe GitHub Wiki
There is two type of scopes in which object path are resolved against.
In iteration using foreach statement or a function argument is invoked,
a new scope for input object is created.
Each newly created scope is stacked on top of the outer one and each scope in
the stack can be retrieved through special variable starting with @:
@0 the current scope, @1 one scope out, and way up to @n.
In addition, the @root variable can access the input object supplied to the template.
In template inclusion, there is a new scope for global variables. This affects where global variables are written to in template.
Global variables are always written in the current global objects. Therefore in case of name collision, global variables declared outside the current global object scope will not be overwritten.
The first segment of an object path are subject to visibility of objects in the stack and global objects. It is tested whether the property is defined on the input or global objects.
To illustrate considering the following scenario:
var input = {
data: {
items: [1, 2, 3]
}
};
waterpipe.pipes.myTemplate = '{{foreach items}}{{[ myVal | "=" | . ] join}}{{/foreach}}';
waterpipe.globals.myGlobal = 'myGlobal';
waterpipe.globals.myVar = 'myVar';
waterpipe('{{data myTemplate}}', input, {
globals: {
myVar: 'myVar redefined'
}
});When the two object path is evaluated, the following objects are tested in sequence for property existence.
For data
- Input object of
waterpipe()(@0or@root) - Global object supplied to
waterpipe() - Global object
waterpipe.globals
For myVal
- Input object scope created by function argument
[ myVal + 1 ](@0) - Input object scope created by
foreach(@1) - Input object of
myTemplate(@2or@root) - Global object scope for
myTemplate - Global object supplied to
waterpipe() - Global object
waterpipe.globals
And by the timemyVal is evaluated for the first iteration, the following name is visible:
{{.}} ➜ 1
{{items}} ➜ [1,2,3]
{{myVar}} ➜ myVar redefined
{{myGlobal}} ➜ myGlobal
{{@0}} ➜ 1
{{@1}} ➜ 1
{{@2}} ➜ {"items":[1,2,3]}
{{@root}} ➜ {"items":[1,2,3]}
{{#key}} 0
{{#index}} 0
{{#count}} 3