13
{% if var is defined %}

and

{% if var is not null %}

Is there a difference in usage of them?

Lindsey D
  • 23,974
  • 5
  • 53
  • 110
nicael
  • 2,382
  • 7
  • 27
  • 48

2 Answers2

14

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.

Lindsey D
  • 23,974
  • 5
  • 53
  • 110
6

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: )

Selvin Ortiz
  • 1,623
  • 11
  • 12