Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony/Twig Set variables in if condition

Tags:

twig

symfony

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

like image 830
Robin Schambach Avatar asked Mar 14 '17 09:03

Robin Schambach


People also ask

What is raw in twig?

3. raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter.


1 Answers

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

like image 192
xabbuh Avatar answered Oct 26 '22 12:10

xabbuh