Twigのテンプレートで条件分岐の書き方です。
実際によく使用するケースなども含めて紹介できたらと思います。
Twigでのif文の使い方
基本的なことをまとめてみます。
式がtrueかどうか判定する
{% if testCase == false %}
<p>"testCase" is false.</p>
{% endif %}
変数の値がtrueかどうか判定する
{# user is variable #}
{% if user %}
<p>{{ user }} is your ID.</p>
{% endif %}
{# users is array. You can also test if an array is not empty #}
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
{% endif %}
ANDやORも使用可能
小文字で使用します。
{% if user.age > 18 and user.age < 40 %}
<p>Youth</p>
{% endif %}
{% if user.city == 'tokyo' or user.city == 'osaka' %}
<p>live in Tokyo or Osaka</p>
{% endif %}
elseifやelseの書き方
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
{{ product.stock }} left
{% else %}
Sold Out
{% endif %}
基本的な使い方は以上です。
Twigでのif文の使用例
if文内で使用できる文法など含めてよく使うケースを紹介したいと思います。
変数が定義されているかチェックする
{% if product.name is defined %}
<div>{{ product.name }} is in stock.</div>
{% endif %}
{# You can use is not defined #}
{% if product.name is not defined %}
<div>the product is out of stock.</div>
{% endif %}
nullかどうか判定する
{% if user is null %}
<p>new user</p>
{% endif %}
値を厳密にチェックする( === の代わりに使用)
{% if user.age is sameas(40) %}
<p>Middle-aged</p>
{% endif %}
正規表現を使用して判定する
{% if phone matches '/^[\\d\\.]+$/' %}
<p>{{ phone }}</p>
{% endif %}
最初の文字や最後の文字を判定する
{% if 'Tokyo' starts with 'T' %}
{% endif %}
{% if 'Tokyo' ends with 'o' %}
{% endif %}
また、気が付いたら使用例を追加していきたいと思います。
Twigおすすめの書籍
Twigだけに特化した書籍は読んだことがないのですが、AmazonのKindleにありました。
これと同じくらいブログでまとめられたらと思います。
[…] 上記matchesは下記記事でも紹介しています。正規表現と比較したい場合など便利です。 [Twig]条件分岐(if文)の使い方まとめ […]
[…] 上記matchesは下記記事でも紹介しています。正規表現と比較したい場合など便利です。 [Twig]条件分岐(if文)の使い方まとめ […]