Home >Backend Development >PHP Tutorial >TWIG's tests learning_PHP tutorial
Making logical judgments. Currently supported are
divisibleby null even odd sameas constant defined empty
divisibleby
Check if it is divisible
{% if loop.index is divisibleby(3) %}
...
{% endif %}
{% if loop.index is divisibleby(3) %}
...
{% endif %}
null
{{ var is null }}
{{ var is null }}
even
Whether the variable is even {{ var is even }}
{{ var is even }}
odd
Whether the variable is an odd number
{{ var is odd }}
{{ var is odd }}
sameas
Check if the addresses of variables are the same{% if foo.attribute is sameas(false) %}
The foo attribute really is the ``false`` PHP value
{% endif %}
{% if foo.attribute is sameas(false) %}
The foo attribute really is the ``false`` PHP value
{% endif %}
constant
Check if the values of variables are the same{% if post.status is constant('Post::PUBLISHED') %}
The status attribute is exactly the same as Post::PUBLISHED
{% endif %}
{% if post.status is constant('Post::PUBLISHED') %}
The status attribute is exactly the same as Post::PUBLISHED
{% endif %}
defined
Test whether the variable is defined{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}
{% if foo['bar'] is defined %}
...
{% endif %}
{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}{% if foo['bar'] is defined %}
...
{% endif %}
empty
Test whether the variable is empty. Empty means: the variable has been defined, but its value is null false or an empty string
{# evaluates to true if the foo variable is null, false, or the empty string #}
{% if foo is empty %}
...
{% endif %}
Excerpted from jiaochangyun’s column