20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Twigで変数・配列を定義・使用する際のちょっとしたメモ

20
Posted at

その1:for文の中で定義した変数・配列はfor文の外では使えない

公式ドキュメントの以下URLページ最下部に記載があります。
http://twig.sensiolabs.org/doc/tags/set.html
以下引用。

ダメな例
{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is NOT available for文の外でfooを呼び出すとエラーになる#}
正しい例
{% set foo = "" %}
{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is available for文の前でfooを定義してあげるとfor文の外でも使える#}

その2:for文の中で配列を追加していく場合は「merge()」を使う

ダメな例
{% set foo = [] %} {# 配列を定義する場合は「""」ではなく「[]」 #}
{% for item in list %}
    {% set foo = [item] %}
{% endfor %}


{# これだと上書きになっちゃいます。 #}
正しい例
{% set foo = [] %}
{% for item in list %}
    {% set foo = foo|merge([item]) %}
{% endfor %}


{# merge()で追加していく#}

その3:dump()を使おう

twig上で変数・配列の中身を確認したい場合はdump()を使う

まとめ

そもそもテンプレート上で配列をセットするのってどうなのよ?という声もありつつ、
データベースからのデータ取得形式やパフォーマンスに応じて適宜活用していければと思います。

20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?