How to check for null in Twig?
Depending on what exactly you need:
is null
checks whether the value isnull
:{% if var is null %} {# do something #}{% endif %}
is defined
checks whether the variable is defined:{% if var is not defined %} {# do something #}{% endif %}
Additionally the is sameas
test, which does a type strict comparison of two values, might be of interest for checking values other than null
(like false
):
{% if var is sameas(false) %} {# do something %}{% endif %}
How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html
{{ my_var | default("my_var doesn't exist") }}
Or if you don't want it to display when null:
{{ my_var | default("") }}
Without any assumptions the answer is:
{% if var is null %}
But this will be true only if var
is exactly NULL
, and not any other value that evaluates to false
(such as zero, empty string and empty array). Besides, it will cause an error if var
is not defined. A safer way would be:
{% if var is not defined or var is null %}
which can be shortened to:
{% if var|default is null %}
If you don't provide an argument to the default
filter, it assumes NULL
(sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):
{% if var|default is empty %}