if

The if statement in Twig is comparable with the if statements of PHP.

Twig の if ステートメントは、PHP の if ステートメントに匹敵します。

In the simplest form you can use it to test if an expression evaluates to true:

最も単純な形式では、式が true と評価されるかどうかをテストするために使用できます。
1
2
3
{% if online == false %}
    <p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %}

You can also test if an array is not empty:

配列が空でないかどうかをテストすることもできます。
1
2
3
4
5
6
7
{% if users %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Note

ノート

If you want to test if the variable is defined, use if users is defined instead.

変数が定義されているかどうかをテストする場合は、代わりに if users isdefined を使用してください。

You can also use not to check for values that evaluate to false:

false と評価される値をチェックしないようにすることもできます。
1
2
3
{% if not user.subscribed %}
    <p>You are not subscribed to our mailing list.</p>
{% endif %}

For multiple conditions, and and or can be used:

複数の条件の場合、and および or を使用できます。
1
2
3
{% if temperature > 18 and temperature < 27 %}
    <p>It's a nice day for a walk in the park.</p>
{% endif %}

For multiple branches elseif and else can be used like in PHP. You can use more complex expressions there too:

複数のブランチの場合は、PHP のように elseif と else を使用できます。より複雑な式も使用できます。
1
2
3
4
5
6
7
{% if product.stock > 10 %}
   Available
{% elseif product.stock > 0 %}
   Only {{ product.stock }} left!
{% else %}
   Sold-out!
{% endif %}

Note

ノート

The rules to determine if an expression is true or false are the same as in PHP; here are the edge cases rules:

式が true か false かを判断するルールは、PHP と同じです。エッジケースのルールは次のとおりです。
Value Boolean evaluation
empty string false
numeric zero false
NAN (Not A Number) true
INF (Infinity) true
whitespace-only string true
string "0" or '0' false
empty array false
null false
non-empty array true
object true