FORSMILE
EN
Twig2021/01/21

[Twig]条件分岐(if文)の使い方まとめ

実際によく使用するケースなども含めて紹介できたらと思います。

ブログ一覧へ / Back to Blog

実際によく使用するケースなども含めて紹介できたらと思います。

Twigでのif文の使い方

式がtrueかどうか判定する

html
{% if testCase == false %}
    <p>"testCase" is false.</p>
{% endif %}

変数の値がtrueかどうか判定する

javascript
{# 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も使用可能

html
{% 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の書き方

css
{% if product.stock > 10 %}
   Available
{% elseif product.stock > 0 %}
   {{ product.stock }} left
{% else %}
   Sold Out
{% endif %}

Twigでのif文の使用例

if文内で使用できる文法など含めてよく使うケースを紹介したいと思います。

変数が定義されているかチェックする

css
{% 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かどうか判定する

html
{% if user is null %}
    <p>new user</p>
{% endif %}

値を厳密にチェックする( === の代わりに使用)

html
{% if user.age is sameas(40) %}
    <p>Middle-aged</p>
{% endif %}

正規表現を使用して判定する

html
{% if phone matches '/^[\\d\\.]+$/' %}
   <p>{{ phone }}</p>
{% endif %}

最初の文字や最後の文字を判定する

css
{% if 'Tokyo' starts with 'T' %}
{% endif %}

{% if 'Tokyo' ends with 'o' %}
{% endif %}

Twigおすすめの書籍

Twigだけに特化した書籍は読んだことがないのですが、AmazonのKindleにありました。

📦
Amazon で関連書籍・ツールを検索
PHP テンプレート Twig
Amazonで探す →(アソシエイトリンク)