1``with``
2========
3
4.. versionadded:: 1.28
5    The ``with`` tag was added in Twig 1.28.
6
7Use the ``with`` tag to create a new inner scope. Variables set within this
8scope are not visible outside of the scope:
9
10.. code-block:: jinja
11
12    {% with %}
13        {% set foo = 42 %}
14        {{ foo }}           foo is 42 here
15    {% endwith %}
16    foo is not visible here any longer
17
18Instead of defining variables at the beginning of the scope, you can pass a
19hash of variables you want to define in the ``with`` tag; the previous example
20is equivalent to the following one:
21
22.. code-block:: jinja
23
24    {% with { foo: 42 } %}
25        {{ foo }}           foo is 42 here
26    {% endwith %}
27    foo is not visible here any longer
28
29    {# it works with any expression that resolves to a hash #}
30    {% set vars = { foo: 42 } %}
31    {% with vars %}
32        ...
33    {% endwith %}
34
35By default, the inner scope has access to the outer scope context; you can
36disable this behavior by appending the ``only`` keyword:
37
38.. code-block:: jinja
39
40    {% set bar = 'bar' %}
41    {% with { foo: 42 } only %}
42        {# only foo is defined #}
43        {# bar is not defined #}
44    {% endwith %}
45