Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``set`` |
| 2 | ======= |
| 3 | |
| 4 | Inside code blocks you can also assign values to variables. Assignments use |
| 5 | the ``set`` tag and can have multiple targets. |
| 6 | |
| 7 | Here is how you can assign the ``bar`` value to the ``foo`` variable: |
| 8 | |
| 9 | .. code-block:: twig |
| 10 | |
| 11 | {% set foo = 'bar' %} |
| 12 | |
| 13 | After the ``set`` call, the ``foo`` variable is available in the template like |
| 14 | any other ones: |
| 15 | |
| 16 | .. code-block:: twig |
| 17 | |
| 18 | {# displays bar #} |
| 19 | {{ foo }} |
| 20 | |
| 21 | The 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 | |
| 30 | Several 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 | |
| 41 | The ``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 #} |