Rolodex McGee
Rolodex McGee

Reputation: 45

Twig - Why are vars defined as false become empty?

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

https://twigfiddle.com/ebbwgf

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

Answers (2)

Veve
Veve

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 %}

https://twigfiddle.com/5g9thl

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 %}

https://twigfiddle.com/m1n1q0

Upvotes: 1

Alvin Bunk
Alvin Bunk

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:

https://twigfiddle.com/yxt1jd

Hope that helps!

Upvotes: 1

Related Questions