it's gonna sound very stupid but I don't know how to write this ternary condition within my twig template.
{% for post in posts %}
<div class="news_text {{ loop.index is odd ? left : right }}">
{{ post.content }}
</div>
{% endfor %}
Can anyone tell me what would be the good syntax pls? :-)
You might try doing this the other way. Create an if and according to the result set output to either left or right.
{% for post in posts %}
{% set output = "right" %}
{% if loop.index is odd %}
{% set output = "left" %}
{% endif %}
<div class="news_text {{ output }}">
{% endfor %}
But if you want to do it your way try:
{% for post in posts %}
<div class="news_text {{ loop.index is odd ? "left" : "right" }}">
{% endfor %}
Instead of using if/else, there actually exists a ternary operator in twig
{{ (isTrue) ? 'true' : 'false' }}
Short-hand syntax is also supported:
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
Official Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With