set

Inside code blocks you can also assign values to variables. Assignments use the set tag and can have multiple targets.

コード ブロック内では、変数に値を割り当てることもできます。割り当ては set タグを使用し、複数のターゲットを持つことができます。

Here is how you can assign the bar value to the foo variable:

バーの値を foo 変数に割り当てる方法は次のとおりです。
1
{% set foo = 'bar' %}

After the set call, the foo variable is available in the template like any other ones:

set 呼び出しの後、foo 変数は他のテンプレートと同様にテンプレートで使用できます。
1
2
{# displays bar #}
{{ foo }}

The assigned value can be any valid Twig expression:

割り当てられる値は、任意の有効な Twig 式にすることができます。
1
2
3
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}

Several variables can be assigned in one block:

複数の変数を 1 つのブロックに割り当てることができます。
1
2
3
4
5
6
{% set foo, bar = 'foo', 'bar' %}

{# is equivalent to #}

{% set foo = 'foo' %}
{% set bar = 'bar' %}

The set tag can also be used to 'capture' chunks of text:

set タグは、テキストのチャンクを「キャプチャ」するためにも使用できます。
1
2
3
4
5
{% set foo %}
    <div id="pagination">
        ...
    </div>
{% endset %}

Caution

注意

If you enable automatic output escaping, Twig will only consider the content to be safe when capturing chunks of text.

自動出力エスケープを有効にすると、Twig は、テキストのチャンクをキャプチャするときに、そのコンテンツのみが安全であると見なします。

Note

ノート

Note that loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible outside the loop itself:

ループは Twig でスコープされることに注意してください。したがって、afor ループ内で宣言された変数は、ループ自体の外ではアクセスできません。
1
2
3
4
5
{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is NOT available #}

If you want to access the variable, just declare it before the loop:

変数にアクセスしたい場合は、ループの前に宣言するだけです:
1
2
3
4
5
6
{% set foo = "" %}
{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is available #}