Language
Variables and scope
Where variables come from and how long they live.
A template gets its variables from the data you render it with, from globals, and from tags that create variables, such as set and for.
Where variables come from
When a template uses a name, Kiln looks for it in this order:
- The parameters of the arrow function it is in.
- Local scopes, from the innermost outwards.
- The template scope: the render data,
props, and top-levelsettags. - Globals registered with the environment.
Functions, filters and tests have their own names, separate from variables. A variable called range never hides the range() function.
Scopes
These tags create a new scope: each for iteration, with, block, macro, include, component and fill. Variables made inside a scope disappear when it ends.
if, apply and autoescape don't create a scope.
Assigning variables
set updates a variable where it already exists. If the variable doesn't exist yet, set creates it in the current scope.
{% set total = 0 %}
{% for item in items %}
{% set total = total + item.price %}
{% endfor %}
Total: {{ total }}
Total: 7
Because total existed before the loop, the loop updates it. A variable first set inside the loop only exists inside the loop.
You can't assign to loop, slots or a global.
Isolated templates
Included templates, components and macros don't see the caller's variables. They only see what you pass them, plus globals. This keeps each template's inputs clear.
{% include "partials/header" with { page, nav } %}