Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Twig and variables as numbers

I'm getting a number from database (let's say, 10) and I want to use it in if/else statement. Please note, that my variable may be equal to 0 or null.

My variable is item.getRate.getRate. I'm showing it in template like this:

{{ item.getRate.getRate | default('0') }}

I try try to do a if statement by doing

{% if item.getRate.getRate == 1 %}something{% endif %}

but it doesn't work.

It is runned in a loop, and one of the items has empty getRate. Could this be the problem? If yes - how can I avoid it?

Upvotes: 0

Views: 1571

Answers (3)

Lighthart
Lighthart

Reputation: 3656

Assuming getRate having a non-zero, non-null value is necessary for this indication of boolean value, as your example suggests:

{% if not(not(item.getRate.getRate)) %} 
    checked="checked"
{% endif %}

Upvotes: 0

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

You can combine both tests to make your code easy to read.

{% if item.getRate.getRate is defined and item.getRate.getRate == 1 %} 
    checked="checked"
{% endif %}

Upvotes: 4

Tomek Buszewski
Tomek Buszewski

Reputation: 7935

I just had to check if variable exists ;)

{% if item.getRate.getRate is defined %}{% if item.getRate.getRate == 1 %} checked="checked"{% endif %}{% endif %}

A little long, but works. Anyone had a better idea? 'Cause it would be great, now it's kinda ugly :))

Upvotes: 1

Related Questions