I'd like to introduce how to use Twig's conditional statements, including some common real-world scenarios.
HOW TO USE IF STATEMENTS IN TWIG
Checking if an expression is true
html
{% if testCase == false %}
<p>"testCase" is false.</p>
{% endif %}Checking if a variable's value is 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 %}Using AND and OR operators
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 %}How to write elseif and else
css
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
{{ product.stock }} left
{% else %}
Sold Out
{% endif %}EXAMPLES OF IF STATEMENTS IN TWIG
I'd like to introduce some common use cases, including the various syntax you can use within Twig's if statements.
Checking if a variable is defined
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 %}Checking for null values
html
{% if user is null %}
<p>new user</p>
{% endif %}Strictly checking values (equivalent to `===`)
html
{% if user.age is sameas(40) %}
<p>Middle-aged</p>
{% endif %}Checking with regular expressions
html
{% if phone matches '/^[\\d\\.]+$/' %}
<p>{{ phone }}</p>
{% endif %}Checking the first or last character
css
{% if 'Tokyo' starts with 'T' %}
{% endif %}
{% if 'Tokyo' ends with 'o' %}
{% endif %}RECOMMENDED BOOKS FOR TWIG
While I haven't personally read any books exclusively dedicated to Twig, I found one on Amazon Kindle.
📦Amazon で関連書籍・ツールを検索
PHP Twig template engine
Amazonで探す →(アソシエイトリンク)
