Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame] | 1 | ``with`` |
| 2 | ======== |
| 3 | |
| 4 | Use the ``with`` tag to create a new inner scope. Variables set within this |
| 5 | scope 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 | |
| 15 | Instead of defining variables at the beginning of the scope, you can pass a |
| 16 | hash of variables you want to define in the ``with`` tag; the previous example |
| 17 | is 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 | |
| 32 | By default, the inner scope has access to the outer scope context; you can |
| 33 | disable 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 %} |