blob: 2d7475227c18169fab0e1cb5fea39694fb44c606 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``if``
2======
3
4The ``if`` statement in Twig is comparable with the if statements of PHP.
5
6In the simplest form you can use it to test if an expression evaluates to
7``true``:
8
9.. code-block:: html+twig
10
11 {% if online == false %}
12 <p>Our website is in maintenance mode. Please, come back later.</p>
13 {% endif %}
14
15You can also test if an array is not empty:
16
17.. code-block:: html+twig
18
19 {% if users %}
20 <ul>
21 {% for user in users %}
22 <li>{{ user.username|e }}</li>
23 {% endfor %}
24 </ul>
25 {% endif %}
26
27.. note::
28
29 If you want to test if the variable is defined, use ``if users is
30 defined`` instead.
31
32You can also use ``not`` to check for values that evaluate to ``false``:
33
34.. code-block:: html+twig
35
36 {% if not user.subscribed %}
37 <p>You are not subscribed to our mailing list.</p>
38 {% endif %}
39
40For multiple conditions, ``and`` and ``or`` can be used:
41
42.. code-block:: html+twig
43
44 {% if temperature > 18 and temperature < 27 %}
45 <p>It's a nice day for a walk in the park.</p>
46 {% endif %}
47
48For multiple branches ``elseif`` and ``else`` can be used like in PHP. You can
49use more complex ``expressions`` there too:
50
51.. code-block:: twig
52
53 {% if product.stock > 10 %}
54 Available
55 {% elseif product.stock > 0 %}
56 Only {{ product.stock }} left!
57 {% else %}
58 Sold-out!
59 {% endif %}
60
61.. note::
62
63 The rules to determine if an expression is ``true`` or ``false`` are the
64 same as in PHP; here are the edge cases rules:
65
66 ====================== ====================
67 Value Boolean evaluation
68 ====================== ====================
69 empty string false
70 numeric zero false
71 NAN (Not A Number) true
72 INF (Infinity) true
73 whitespace-only string true
74 string "0" or '0' false
75 empty array false
76 null false
77 non-empty array true
78 object true
79 ====================== ====================