How to write if statement in Twig template.
I would like to introduce some cases that are often used in practice.
Official:if – Documentation – Twig
How to use if statements in Twig
Let’s summarize the basics.
Determine if the expression is true
{% if testCase == false %}
<p>"testCase" is false.</p>
{% endif %}
Determine if the value of the variable is 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 and OR can also be used
{% 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 %}
How to write else if and else
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
{{ product.stock }} left
{% else %}
Sold Out
{% endif %}
That’s all for basic usage.
Example of using if statement in Twig
I would like to introduce a case that is often used, including the grammar that can be used in the if statement.
Check if variable is defined
{% 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 %}
Determine if null
{% if user is null %}
<p>new user</p>
{% endif %}
Strictly check the value (use instead of ===)
{% if user.age is sameas(40) %}
<p>Middle-aged</p>
{% endif %}
Determine using regular expressions
{% if phone matches '/^[\\d\\.]+$/' %}
<p>{{ phone }}</p>
{% endif %}
Determine the first or last character
{% if 'Tokyo' starts with 'T' %}
{% endif %}
{% if 'Tokyo' ends with 'o' %}
{% endif %}
Also, if you notice it, I would like to add usage examples.
[…] The above matches is also introduced in the following article. This is useful when you want to compare with a regular expression. [Twig] Summary of how to use if statement […]