Symfony/Twig Set variables in if condition - 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

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

You can set it with a ternary operator.
{% set result = condition ? "a": "b" %}

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 !

Related

Set a new value depending on what the original value is?

In Drupal views, I have a twig variable available to me called {{ name }}. This stores a list of taxonomy terms depending on the type of content used. I currently have a function running something like this that works:
{% if name == "Tax1" %}
Download
{% elseif name == "Tax2" %}
Download
{% endif %}
However, I feel like there is a better way for me to go about doing this. As an example isn't something like this supposed to work?
{%
set newval = [
name == "Tax1" ? 'file1.pdf' : 'file2.pdf'
]
%}
Download
Pretty much what I'm trying to state above is, if the value of name is equal to "Tax1", print out file1.pdf, else print file2.pdf.
I have very basic twig knowledge and I haven't touched it in a couple years so if anyone could help me out with this, that would be great.
Thanks to #DarkBee for the help. I must have been overthinking as the answer was fairly simple.
The below solution worked for what I was initially asking:
Download
However, I ended up needing a third default option if not the first two so the below code is what I ended up using:
{% if name == "Tax1" or name == "Tax2" %}
Download
{% else %}
<span class="stat">Other Option</span>
{% endif %}

Set default value if null in twig

I am looping my results in twig view..
{% for item in items %}
<li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
{% endfor %}
I want to set default value 'User unknown' if the user id in database is NULL .
Like: {% if item.userId is null %} --> than set default value
Note: I am aware of using if else here but as I have this fistName - lastName in numerous palace, I wanted to avoid using if else in every part. I wanted to set that default value everywhere in case userId is null without repeating the code in every place.
How can I accomplish that?
EDIT
You can set a variable by using:
{% set name = item.userId is null ? 'User unknown' : item.userId.firstName ~ ' ' ~ item.userId.lastName %}
If by setting you mean outputting 'User unknown', a simple if else statement would do the trick
{% for item in items %}
{% if item.userId is null %}
<li>User unknown</li>
{% else %}
<li> {{ item.userId.firstName }} {{ item.userId.lastName }} </li>
{% endif %}
{% endfor %}
It may be easier to set defaults in the code that is rendering the output, where items is being sent to Twig. array_merge is often used for this - $item = array_merge($defaultItem, $item);. Here, $item overrides the value set in defaults.
Within the templates, you can also use the null-coalescing operator ?? on individual fields: {{ item.userId.firstName ?? 'unknown firstName' }}
Maybe a bit late, but Twig seems to have a filter for default values:
https://twig.symfony.com/doc/2.x/filters/default.html

Symfony2 Twig Conditional Template Name

I'm looking for a way to check in my twig template if the name of the template contains a special word. If that is the case I want to proceed with assigning some stuff. Here is a general idea I have in mind.
{% if [sth like app.request.template_name or sth like that] in `product` %}
// Do some stuff
{% endif % }
Can you guys help me with this?
If you're creating separate template files then you'll know the names and can hardcode the values:
template_1.html.twig:
{% set some_var = 1 %}
{% set another_var = 2 %}
template_2.html.twig:
{% set custom_var = 5 %}
Update:
If you want the template name, you can use:
{% if 'product' in _self.getTemplateName() %}
{# Do stuff #}
{% endif %}

Twig / Symfony2 - using a variable inside array merge

{% set var_name1 = "hello" %}
{% set var_name2 = "there" %}
{% array1|merge({var_name1: var_name2}) %}
I was hoping the code above would add this to array1:
hello:there
...but it adds:
var_name1:there
I've tried wrapping {{ }} around var_name1. Is it possible to add a record to an array and use a variable for the key?
Enclose the key name in brackets:
{% array1|merge({(var_name1): var_name2}) %}
Note that if var_name1 is a numeric value, it won't work.
You'll have to concat it with a string value :
{% set array1 = array1|merge({(var_name1~'_'): var_name2}) %}

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?
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 %}
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 :))
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 %}

Resources