Twig if文の基本
Twigの条件分岐は {% if 条件 %} で始め、{% endif %} で閉じます。elseやelseifも利用できます。
twig
{% if user.isActive %}
<p>{{ user.name|e }}さん、ようこそ</p>
{% elseif user is defined %}
<p>アカウントは停止中です</p>
{% else %}
<p>ログインしてください</p>
{% endif %}empty・defined・notで安全に判定する
値が渡らない可能性がある場合はdefinedを先に確認します。空文字、空配列、nullなどの確認にはemptyが使えます。
twig
{% if products is defined and products is not empty %}
{{ products|length }}件の商品があります
{% else %}
商品はありません
{% endif %}and / orを使う複合条件
twig
{% if user.isActive and (user.role == 'admin' or user.role == 'editor') %}
<a href="/admin">管理画面</a>
{% endif %}- ▸条件を括弧でまとめ、評価順を明確にする
- ▸未定義の可能性がある変数はdefinedで確認する
- ▸表示時はautoescapeの設定を確認し、必要に応じてeフィルターを使う
