Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.
{% if var is defined %}

and

{% if var is not null %}

Is there a difference in usage of them?

share|improve this question
add comment

2 Answers 2

up vote 8 down vote accepted

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.

share|improve this answer
1  
Now I understand )) –  nicael Jun 20 at 20:40
1  
You're a machine, Lindsey. –  Brad Bell Jun 20 at 21:40
    
Apparently there's some merit to this "gamification" concept. ;) –  Lindsey D Jun 20 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. –  Brandon Kelly Jun 21 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 Jun 21 at 5:47
add comment

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

share|improve this answer
    
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 Jun 20 at 20:52
1  
No worries bro, you answer is much better: ) Keep up the good work! –  Selvin Ortiz Jun 20 at 20:54
2  
@LindseyD I agree! Give others (me) a chance. In fact, please start emailing me answers. –  Matt Stein Jun 20 at 20:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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