Twigのforまとめ

Twigでループ処理を書きたいときに使う for は結構いろんな書き方ができるのでまとめとく。
とは言っても、ドキュメント見れば全部載ってるけども。

連続した値を扱いたいとき

https://twig.symfony.com/doc/2.x/tags/for.html#for

.. 演算子を使うと便利。

{% for i in 0..10 %}
    {{ i }},
{% endfor %}
{# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, #}

{% for i in 'a'..'z' %}
    {{ i }},
{% endfor %}
{# a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, #}

{% for i in 'a'|upper..'z'|upper %}
    {{ i }},
{% endfor %}
{# A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, #}

ループ内で使える変数

https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

{% for i in '0'..'10' %}
    {{ loop.index }}
{% endfor %}
{# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, #}

{% for i in '0'..'10' %}
    {{ loop.index0 }}
{% endfor %}
{# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, #}

{% for i in '0'..'10' %}
    {{ loop.revindex }}
{% endfor %}
{# 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, #}

{% for i in '0'..'10' %}
    {{ loop.revindex0 }}
{% endfor %}
{# 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, #}
    
{# 最初の要素のときだけtrue #}
{% for i in '0'..'10' %}
    {{ loop.first }},
{% endfor %}
{# 1, , , , , , , , , , , #}

{# 最後の要素のときだけtrue #}
{% for i in '0'..'10' %}
    {{ loop.last }},
{% endfor %}
{# , , , , , , , , , , 1, #}

{# 配列の長さを返す #}
{% for i in '0'..'10' %}
    {{ loop.length }},
{% endfor %}
{# 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, #}

loop.parent はちょっとわかりづらい。
ループがネストしている場合に外側のループにアクセスできる。

{% for i in 0..3 %}
    {% for j in 'a'..'c' %}
        [{{ loop.parent.loop.index }}, {{ loop.index }}]<br>
    {% endfor %}
{% endfor %}
{#
[1, 1]
[1, 2]
[1, 3]
[2, 1]
[2, 2]
[2, 3]
[3, 1]
[3, 2]
[3, 3]
[4, 1]
[4, 2]
[4, 3]
#}

条件を指定してループをまわす

https://twig.symfony.com/doc/2.x/tags/for.html#adding-a-condition

if を使うことで条件を指定できる。

{% for i in 0..10 if i % 2 == 0 %}
    {{ i }},
{% endfor %}
{# 0, 2, 4, 6, 8, 10, #}

そのほかのおべんりなやつ

else を使うと空配列だったときの処理が書ける。

{% for i in [] %}
    {{ i }}
{% else %}
    empty!
{% endfor %}
{# empty! #}

キーを取得したいとき。
キーだけの取得もできるけど大抵は値とセットで欲しい。

{% for key in ['taro', 'ichiro', 'hanako']|keys %}
    {{ key }}
{% endfor %}
{# 0 1 2 #}

{% for key, value in ['taro', 'ichiro', 'hanako'] %}
    {{ key }}:{{ value }}
{% endfor %}
{# 0:taro 1:ichiro 2:hanako #}

slice とかと組み合わせたり。

{% for key, value in ['太郎', '次郎', '三郎', '四郎', '五郎']|slice(2, 4) %}
    {{ key }}:{{ value }}
{% endfor %}
{# 0:三郎 1:四郎 2:五郎 #}

ざっとまとめたけど色々できるな。。