When testing for a variable in a template these two appear to do the same thing. I've read CruftlessCraft's article on How to check for undefined variables but can't see an explanation of why I should use one over the other. In his examples (below) I note that only the default filter includes "" in the list of results, is that correct or significant? Is one faster or more efficient?

{% if twigVariable|default %}
    Value is set and not empty
{% else %}
    Value is either undefined, false, 0, null, "", [] or {}
{% endif %}


{% if twigVariable ?? false %}
    The value is set and not empty
{% else %}
    Value is either undefined, false, 0, null, [] or {}
{% endif %}

Does it make any difference if I don't need a fallback or the else and am just wrapping it around a div that shouldn't be shown if the variable doesn't have any usable content?

1 Answer 1


So things like the null coalescing operator make it easier to chain things, so if you have a number things to fall back on, it's much neater to write:

{% set woof = bark ?? howl ?? growl ?? null %}

...then it is to try to chain that all together with | default filters.

Something that may also make your life easier is the Empty Coalesce plugin, so you can write:

{% set woof = bark ??? howl ??? growl ??? null %}

What's the difference? The null coalescing operator only checks for null, so if bark = "" then it'll choose that, which often isn't what you want for strings.

There's a writeup of all of this in Handling Errors Gracefully in Craft CMS article.

Now, what is going to be more performant? Unless you're in a massive inner loop (which we should avoid in a templating language anyway), I doubt it'll matter. PHP code is transpiled to a bytecode that often gets cached, it should be fine.

But in theory, ?? and ??? are probably marginally faster.

  • So am I right in thinking that if I don't want any fallback options the default filter is the best choice to test for existence of anything usable? I'd rather not be reliant on a third party plugin if I didn't need to, but if I did need to I'd be happy if it was one of yours. I had read your excellent Handling Errors article but wasn't 100% sure it was all valid for Craft 3, as there are so many small subtle changes that are easy to miss when moving from Craft 2.
    – Paul Frost
    Commented Sep 22, 2018 at 8:22
  • Use whatever is the most readable to you, imo. That "Handling Errors" article was written for Craft 3, but it applies for Craft 2 as well. I think it's totally fine and understandable to just use the default filter if your case is simple. Commented Sep 24, 2018 at 14:35

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.