Tests
Tests in Twig are used with the is operator to check values.
twig-tests
{% if value is test_name %}
{% if value is not test_name %}
Tests
constant
Checks if a value equals a PHP constant:
constant
{% if status is constant('App\\Entity\\User::STATUS_ACTIVE') %}
User is active
{% endif %}
{# Object constant #}
{% if status is constant('STATUS_ACTIVE', user) %}
defined
Checks if a variable is defined:
defined
{% if user is defined %}
{{ user.name }}
{% endif %}
{% if user.address is defined %}
{{ user.address.city }}
{% endif %}
tip
defined only checks whether a variable exists, not its value. A variable can be defined and equal to null.
divisible by
Checks if a number is evenly divisible:
divisible by
{% if loop.index is divisible by(3) %}
{# Every third element #}
<hr>
{% endif %}
{% for i in 1..20 %}
{% if i is divisible by(5) %}
{{ i }} is divisible by 5
{% endif %}
{% endfor %}
empty
Checks if a value is "empty":
empty
{% if items is empty %}
<p>The list is empty</p>
{% endif %}
{% if user.name is not empty %}
{{ user.name }}
{% endif %}
Considered empty: false, 0, null, '' (empty string), [] (empty array).
even
Checks if a number is even:
even
{% for user in users %}
<tr class="{{ loop.index is even ? 'even' : 'odd' }}">
<td>{{ user.name }}</td>
</tr>
{% endfor %}
odd
Checks if a number is odd:
odd
{% if value is odd %}
Odd number
{% endif %}
iterable
Checks if a value can be iterated over (an array or an object implementing Traversable):
iterable
{% if items is iterable %}
{% for item in items %}
{{ item }}
{% endfor %}
{% else %}
{{ items }}
{% endif %}
null
Checks if a value equals null:
null
{% if value is null %}
Value is not set
{% endif %}
{# none is an alias for null #}
{% if value is none %}
same as
Strict comparison (===), checks both type and value:
same as
{% if value is same as(false) %}
{# Exactly false, not 0, '' or null #}
{% endif %}
{% if count is same as(0) %}
{# Exactly 0, not false or '' #}
{% endif %}
mapping
Checks if a value is an associative array (hash):
mapping
{% if data is mapping %}
{# This is an associative array (hash) #}
{% for key, value in data %}
{{ key }}: {{ value }}
{% endfor %}
{% endif %}
sequence
Checks if a value is a sequential (indexed) array:
sequence
{% if data is sequence %}
{# This is a regular array with numeric keys #}
{% for item in data %}
{{ item }}
{% endfor %}
{% endif %}
Combining tests
Combining tests
{# Negation #}
{% if value is not empty %}
{% if user is not defined %}
{% if number is not even %}
{# With logical operators #}
{% if user is defined and user.name is not empty %}
{{ user.name }}
{% endif %}
{% if items is iterable and items is not empty %}
{% for item in items %}
{{ item }}
{% endfor %}
{% endif %}