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?
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.
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 ).
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.
You need to declare the var in each check so {% if var is defined and var is not null %}
.
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) %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With