blob: 7a3a784f50385ef528492a6923414c872f7f3089 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``set``
2=======
3
4Inside code blocks you can also assign values to variables. Assignments use
5the ``set`` tag and can have multiple targets.
6
7Here is how you can assign the ``bar`` value to the ``foo`` variable:
8
9.. code-block:: twig
10
11 {% set foo = 'bar' %}
12
13After the ``set`` call, the ``foo`` variable is available in the template like
14any other ones:
15
16.. code-block:: twig
17
18 {# displays bar #}
19 {{ foo }}
20
21The assigned value can be any valid :ref:`Twig expression
22<twig-expressions>`:
23
24.. code-block:: twig
25
26 {% set foo = [1, 2] %}
27 {% set foo = {'foo': 'bar'} %}
28 {% set foo = 'foo' ~ 'bar' %}
29
30Several variables can be assigned in one block:
31
32.. code-block:: twig
33
34 {% set foo, bar = 'foo', 'bar' %}
35
36 {# is equivalent to #}
37
38 {% set foo = 'foo' %}
39 {% set bar = 'bar' %}
40
41The ``set`` tag can also be used to 'capture' chunks of text:
42
43.. code-block:: html+twig
44
45 {% set foo %}
46 <div id="pagination">
47 ...
48 </div>
49 {% endset %}
50
51.. caution::
52
53 If you enable automatic output escaping, Twig will only consider the
54 content to be safe when capturing chunks of text.
55
56.. note::
57
58 Note that loops are scoped in Twig; therefore a variable declared inside a
59 ``for`` loop is not accessible outside the loop itself:
60
61 .. code-block:: twig
62
63 {% for item in list %}
64 {% set foo = item %}
65 {% endfor %}
66
67 {# foo is NOT available #}
68
69 If you want to access the variable, just declare it before the loop:
70
71 .. code-block:: twig
72
73 {% set foo = "" %}
74 {% for item in list %}
75 {% set foo = item %}
76 {% endfor %}
77
78 {# foo is available #}