twigでランダムに配列や数値を選ぶ
twigでランダムに配列や数値を出す方法を調べたのでシェア
今回の僕の場合、
<img href="/img/img_01.jpg">
上みたいなときに、ランダムでimg_02.jpgやimg_03.jpgを出すように言われました。
この場合、
<img href="/img/img_0{{random(2) + 1}}.jpg">
でうまくいきます。
random(n) は0 ~ n-1までの数値を出すので、今回のように1 ~ nを出したい場合は +1する必要があります。
ちなみに他の使い方もできて、ドキュメントには配列からランダムに選ぶ方法なども載ってます。
参考URL
random - Documentation - Twig - The flexible, fast, and secure PHP template engine
{{ random(['apple', 'orange', 'citrus']) }} {# example output: orange #} {{ random('ABC') }} {# example output: C #} {{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #} {{ random(5) }} {# example output: 3 #}