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