Twig and variables as numbers - symfony

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

Related

How would I write multiple "if" conditions in one line in timber/twig?

I have a situation where I would like to write multiple "if" condition in one line such as example: {% if room_status == 'For Rent' and not 'Booked' %} this is obviously not working but you get the picture of what I am trying to accomplish.
But have no idea how to write this other that doing this:
{% if room_status == 'For Rent'%}
{% if room_status != 'Booked' %}
{# <Then run some code here> #}
{% endif %}
{% endif %}
Any suggestions greatly appreciated!
From the Twig If Documentation:
For multiple conditions, and and or can be used:
{% if temperature > 18 and temperature < 27 %}
<p>It's a nice day for a walk in the park.</p>
{% endif %}
So, in your case this should work:
{% if room_status == 'For Rent' and room_status != 'Booked' %}
{# <Then run some code here> #}
{% endif %}
Although it seems to me that you don't really need the second check. The room_status variable can only contain one value, right? It can't be both 'For Rent' and 'Booked' at the same time, it's either one or the other.

Twig - loop default value

I am trying to print array from the cotroller into the twig temlate. I want to print "-" whenever array is NULL. My problem is that in for-loop case it writes nothing, however single row working fine. Is there some simple way how to do it correctly?
this is not working as i expected
{% for key in keywords|default('-') %}
{{ key~', '}}
{% endfor %}
this is working
{{ key |default('-')}}
You can use an {% else %} construct on a for loop to do something else if the array is null:
{% for key in keywords %}
{{ key~', '}}
{% else %}
-
{% endfor %}
See the documentation here.

Twig variable from one loop in another doesn't work

I have two loops in Twig. One is to check the stock level of a product, the other is to display some product options. I'm trying to create a variable from one loop which I can use inside the other to add a class name to a list(s).
I can't get that to work. Any help is more then welcome...
What I have is this:
{% set stockLevel = '' %}
{% for variant in product.variants %}
{% set stockLevel = variant.stock.level %}
{{ stockLevel }} // gives 1 0 1 1 (So all sizes except the second one are available)
{% endfor %}
{% for option in product.options %}
<ul class="optionslist">
{% if option.values %}
{% for value in option.values %}
<li class=" {% if stockLevel == 0 %}not_on_stock {% endif %}" >
<a class="item">etc...</a>
</li>
{% endfor %}
{% endif %}
</ul>
{% endfor %}
I believe there is something wrong the way you are handling your data. Right now, event if your variable was accessible in your second for loop, the value of it would be the one set lastly and your script would've failed anyway.
I can suggest a bit of a hacky way, feel free to improvise or use the idea behind it.
Say, we assign an empty array:
{% set variantsArray = [] %}
Then, we will use the filter merge to fill it with some dummy data(that's where your first loop comes into play)
{% for number in 1..5 %}
{% set variantsArray = variantsArray | merge([number]) %}
{% endfor %}
Then to be sure, we can access all the values there, we will just dump it out(that's where your second loop comes)
{% for index in 1..3 %}
{{ dump(variantsArray) }}
{% endfor %}
The following dump generated:
array:5 [▼
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
]
Hope you got the idea. Any suggestions are kindly welcome.
I am not sure what you are trying to do, how do you get your stock level from the variants? i think it is better to have a service function which help you get your stock level by product, the code would be cleaner :
controller action
$stock_helper = $this->container->get('stockhelper_service');
$stocklevel = $stock_helper->getStockLevelByProduct($product); //getstocklevelbyproduct handle your logic and return the stock level integer.
pass this variable to the twig.
One variable in your twig, no loops there, clean view, understandable code in your view and action.
Ok, I found the solution. The trick is to "connect" both values. Like so:
{% for option in product.options %}
{% if option.values %}
<ul id="product_configure_option2_{{ option.id }}" data-id="{{ option.id }}">
{% for value in option.values %}
{% set stock = null %}
{% for variant in product.variants **if variant.title == (option.title ~ ': ' ~ value.title)** %}
{% set stock = variant.stock %}
{% endfor %}
<li value="{{ value.id }}"{% if not stock.available %} class="not_on_stock"{% endif %}>{{ value.title }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}

Twig and Symfony2 - test if a number is even

I would like to create a table with different color for each even row. For that, I created the css and I will have to check in my twig template if the iteration index is even or not.
{% if loop.index == "even" %}
But how to check if a number is even in twig? Thank you.
Twig has a built in "even" test:
{% if (loop.index is even) %}
...your code here
{% endif %}
You have to use the "modulo" operator as follow :
{% if(loop.index%2 == 0) %}
...your code here
{% endif %}
I think a more cleaner way would be:
{{ loop.index is odd ? 'is-odd' : 'is-even' }}

Twig: filter in an if condition

I want to use an filter in an if condition in Twig. The reason for this is a Symfony2 attribute, which I can't compare directly, I have to change it beforehand. I have started with this code:
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\controller\name' %}
do something
{% endif %}
Unfortunately this does not function. So I thought I would use set before the comparison:
{% set controller = app.request.attributes.get('_controller')|split('::')|first %}
{% if controller == 'some\controller\name' %}
do something
{% endif %}
{{ controller }} {# would print 'some\controller\name' #}
Guess what? "do something" is not printed, even if the variable controller now exists and has the value I compare it with. What am I doing wrong?
Ok I tested it, Twig has a strange behavior. "\" is escaped or something like this.
I extended my twig environement with the var_dump function, check this:
{{ var_dump("Sybio\Bundle\WebsiteBundle\Controller\MainController") }}
//string(48) "SybioBundleWebsiteBundleControllerMainController"
{{ var_dump(app.request.attributes.get('_controller')|split('::')|first) }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
{{ var_dump("Sybio\\Bundle\\WebsiteBundle\\Controller\\MainController") }}
// string(52) "Sybio\Bundle\WebsiteBundle\Controller\MainController"
That's why your test is always false.
You need to double the backslashes of your compared string...
{% if app.request.attributes.get('_controller')|split('::')|first == 'some\\controller\\name' %}
do something
{% endif %}

Resources