Raphael_b
Raphael_b

Reputation: 1510

TWIG: is defined and is not null

quick question I have a var and I want to check if it is defined (to avoid have a bug in the render) and if it is not null (to display something with a Else if null)

{% if var is not null %} works

{% if var is defined %} works

{% if var is not null and is defined %} does not work any idea of the correct syntax?

EDIT the workaround will be:

{% if var is defined %}
    {% if var is not null %}
        {{ var }}
    {% else %}
        blabla
    {% endif %}
{% endif %}

That a lot of code for something simple... ideas how to merge the two IF?

Upvotes: 42

Views: 103277

Answers (6)

oshell
oshell

Reputation: 9103

Wrong

{% if var is not null and var is defined %}

This does not work because a variable which is null in twig is defined, but if you check for null first and it is not defined it will throw an error.

Correct

{% if var is defined and var is not null %}

This will work because we check if it is defined first and will abord when not. Only if the variable is defined we check if it is null.

Upvotes: 83

Baishu
Baishu

Reputation: 1591

This might be the shortest syntax for what you are trying to check

{% if var ?? false %}

Upvotes: 1

Kaizoku Gambare
Kaizoku Gambare

Reputation: 3413

I use this one that is a bit shorter. It's not 100% equal to the null test but it suit my usage.

{% if var is defined and var %}

Upvotes: 2

Daniel Howard
Daniel Howard

Reputation: 5158

I have always used the ?? operator to provide a 'default' value when I know a variable might not be defined. So {% if (var is defined and var is not null) %} is equivalent to:

{% if (var ?? null) is not null %}

If you just want to check whether a value that might not be defined is truthy you can do this:

{% if (var ?? null) %}

Upvotes: 9

John B
John B

Reputation: 169

Just like any other programming language, you will still need to make a reference to the variable for each check you make.

{% if var is defined and not null %}

This won't work because after checking is defined twig doesn't know what you're attempting to check for a null on. The solution:

{% if (var is defined) and (var is not null) %}
... code
{% endif}

The parenthesis are not necessarily required. It's more of a preference for readability. I hope this helps.

Upvotes: 3

qooplmao
qooplmao

Reputation: 17759

You need to declare the var in each check so {% if var is defined and var is not null %}.

Upvotes: 6

Related Questions