# 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:

1. The parameters of the arrow function it is in.
2. Local scopes, from the innermost outwards.
3. The template scope: the render data, `props`, and top-level `set` tags.
4. [Globals](https://kilnlang.com/docs/api/extending/#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.

page.kiln:

```kiln
{% set total = 0 %}
{% for item in items %}
	{% set total = total + item.price %}
{% endfor %}
Total: {{ total }}
```

Output:

```html
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.

```kiln
{% include "partials/header" with { page, nav } %}
```
