13
{% if var is defined %}

and

{% if var is not null %}

Is there a difference in usage of them?

2 Answers 2

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.

5
  • 1
    Now I understand ))
    – nicael
    Commented Jun 20, 2014 at 20:40
  • 1
    You're a machine, Lindsey.
    – Brad Bell
    Commented Jun 20, 2014 at 21:40
  • Apparently there's some merit to this "gamification" concept. ;)
    – Lindsey D
    Commented Jun 20, 2014 at 21:45
  • Technically 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
  • Very good point @BrandonKelly, I actually learned that a few hours after I posted this answer. I'll go ahead and update my answer. Thanks!
    – Lindsey D
    Commented Jun 21, 2014 at 5:47
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: )

3
  • Hey dude, sorry for simultaneously posting! I should probably ease up a bit and give others a chance to answer a few questions. :)
    – Lindsey D
    Commented Jun 20, 2014 at 20:52
  • 1
    No worries bro, you answer is much better: ) Keep up the good work! Commented Jun 20, 2014 at 20:54
  • 2
    @LindseyD I agree! Give others (me) a chance. In fact, please start emailing me answers.
    – Matt Stein
    Commented Jun 20, 2014 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.