Tests
defined
The defined test allows you to verify if a variable exists in the current context.
Basic Usage:
To check if a variable named foo is defined:
{% if foo is defined %}
...
{% endif %}Checking Attributes on Variable Names:
If you wish to ascertain the existence of an attribute or key on a variable:
{% if foo.bar is defined %}
...
{% endif %}Or, for array-style access:
{% if foo['bar'] is defined %}
...
{% endif %}Using Multiple Variables in Conditions:
When the defined test is part of a condition that uses multiple variables or involves method calls, ensure that all variables involved are defined:
{% if var is defined and var.foo is defined %}
...
{% endif %}divisible by
The divisible by test helps determine if a variable's value can be divided by a specific number without leaving a remainder.
Usage:
Here's an example that checks if the index variable is divisible by 3:
{% if index is divisible by(3) %}
...
{% endif %}Using this test can be helpful in scenarios where you want to apply certain conditions or formatting based on the divisibility of a number, such as creating rows in a grid system or adding separators.
empty
The empty test allows you to verify whether a variable is considered "empty." The following values are considered as empty:
An empty string (
'')An empty array (
[])An empty hash (an array without any key-value pairs)
The boolean value
falseThe value
null
Usage:
Here's how you can use the empty test:
{% if foo is empty %}
...
{% endif %}By leveraging this test, you can effectively handle scenarios where the presence or absence of data impacts the template's rendering.
even
The even test helps in verifying whether a given number is even.
Usage:
Here's how you can use the even test:
{{ var is even }}If var holds an even number, this expression will return true. Otherwise, it will return false.
It can be particularly useful in scenarios where you need to apply conditional formatting or processing based on the even-ness of a number.
iterable
The iterable test can be used to check if a variable is either an array.
Usage:
Here's a practical usage of the iterable test:
{% if users is iterable %}
{% for user in users %}
Hello {{ user }}!
{% endfor %}
{% else %}
{# users is not an array; perhaps it's a string. #}
Hello {{ users }}!
{% endif %}By using the iterable test, you can ensure that the variable can be looped over with a for loop, and if not, you can handle it differently, like treating it as a string.
null
The null test can be used to check if a variable is null.
Usage:
Here's how you can use the null test:
{{ var is null }}odd
The odd test can be used to determine if a given number is odd.
Usage:
Here's how you can use the odd test:
{{ var is odd }}This will return true if the value of var is an odd number.
Last updated