{% if var is defined %}
and
{% if var is not null %}
Is there a difference in usage of them?
is defined
- The variable has been defined, and set to any value (or null
).
is not null
- The variable has been defined, and is specifically not null
.
In PHP terms, it's like the difference between is_null()
vs. checking whether the variable exists using get_defined_vars()
(see this Stack Overflow thread for a little more clarity)
Try this experiment... Without setting myVar
, put this in your template:
{{ (myVar is defined) }}
Since that equates to false
, nothing will appear in your template. Now change it to this:
{{ (myVar is not null) }}
That will actually throw an error, since myVar
was never defined.
is null
is a test, too. Anything starting with “is” or “is not” is a test. is null
is just testing for a null value, whereas is defined
is testing for whether the value exists at all.
Commented
Jun 21, 2014 at 5:42
The first statement checks for the existence of var
, the second checks that it has a value other than null
and will throw and error if var
does not exist.
If you're not sure whether a variable exists, you should check if it exists first then check for its value to be safe.
You could combine both statements like so {% if var is defined and var is not null %}
or use empty, not empty
if you're feeling fancy: )