Robin Schambach
Robin Schambach

Reputation: 846

Symfony/Twig Set variables in if condition

I know this is really trivial and not that important but it could save me some lifetime... You know you can declare variables in PHP in a if block

if( $row = $sql->fetch ){
    //do something with the $row if $row = null this part is skipped
}

In twig I can't do for example (set image = object.image, if my object has no image, the variable image becomes null and the if statement does not become true

{% if image = object.image %}
    <img src="{{ image.getUrl() }}"> //and so on
{% endif %}

Instead I have to make it this way (check if the object has an image, if yes save it to new variable and do some stuff with it)

{% if object.image %}
    {% set image = object.image %}
    <img src="{{ image.getUrl() }}"> //and so on
{% endif %}

Of course I know this is no first world problem and you may think my question is useless but I have to write those "longer" statements many times a day so I could be few minutes faster in the end. So is there a syntax that allows me to set variables in an if block instead of comparing them?

Thank you very much

EDIT
I't the same like this Can I define a variable in a PHP if condition? just in twig

Upvotes: 6

Views: 23274

Answers (4)

Dario Zadro
Dario Zadro

Reputation: 1284

Setting a variable based on a condition is absolutely possible!

{% set variable = (condition == 1) ? 'this' : 'that' %}

The condition can be evaluated against true, false, or another variable as well.

Upvotes: 0

Tushar Wasson
Tushar Wasson

Reputation: 556

You can set it with a ternary operator.

{% set result = condition ? "a": "b" %}

Upvotes: 8

xabbuh
xabbuh

Reputation: 5881

No, there is no way to declare a variable inside an if tag. Variables can only be set using the set tag.

Upvotes: 10

You can use (check here for more help) :

{% if object.image is defined or object.image is not null %}
   <img src="{{ image.url }}">
{% endif %}

Hope this helps !

Upvotes: -1

Related Questions