Reputation: 45
Define a twig var as true, and it has a value of '1'.
Define another var as false, and it has no value. Why is that?
{% set myOtherVar = true %}
{{ myOtherVar }}
This outputs '1'
{% set myVar = false %}
{{ myVar }}
This outputs nada
This is bothersome because simple logic like this fails:
{% set myVar = false %}
{% if myVar is not empty and not myVar %}
stuff
{% endif %}
Upvotes: 4
Views: 1444
Reputation: 6758
false
is equivalent to ''
for empty
:
{% set myVar = '' %}
{% if myVar is empty %}
stuff
{% endif %}
{% set myOtherVar = false %}
{% if myVar is empty %}
other stuff
{% endif %}
Depending on what you want to do, you can test if the variable exists with defined
:
{% set myVar = false %}
{% if myVar is defined and not myVar %}
stuff
{% endif %}
Upvotes: 1
Reputation: 7764
Because you are using set to set the variable as a boolean. So you need to use it as a boolean. You can't print the value.
You might do your logic something like this:
{% set myOtherVar = true %}
{% set myVar = false %}
{% if not myVar %}
myVar is false
{% endif %}
{% if myOtherVar %}
myOtherVar is true
{% endif %}
Here is a twigfiddle showing it working properly:
Hope that helps!
Upvotes: 1