Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TWIG: is defined and is not null

Tags:

twig

symfony

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?

like image 769
Raphael_b Avatar asked Jul 09 '15 10:07

Raphael_b


People also ask

How do I check if a twig is not empty?

should check whether the variable is null or empty. If you want to see if it's not null or empty just use the not operator. See the docs: empty.

How do you check variables in twig?

By setting strict_variables to false If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).


3 Answers

Wrong

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

This does not work because a variable which is null in twig is defnied, 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.

like image 155
oshell Avatar answered Oct 08 '22 19:10

oshell


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

like image 27
qooplmao Avatar answered Oct 08 '22 20:10

qooplmao


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) %}
like image 6
Daniel Howard Avatar answered Oct 08 '22 20:10

Daniel Howard