1``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:: jinja 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:: jinja 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:: jinja 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:: jinja 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:: jinja 52 53 {% if kenny.sick %} 54 Kenny is sick. 55 {% elseif kenny.dead %} 56 You killed Kenny! You bastard!!! 57 {% else %} 58 Kenny looks okay --- so far 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 whitespace-only string true 72 empty array false 73 null false 74 non-empty array true 75 object true 76 ====================== ==================== 77