Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - ternary conditional operator

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

like image 334
Cellendhyll Avatar asked Jun 11 '26 22:06

Cellendhyll


2 Answers

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 %}
like image 57
Fiffe Avatar answered Jun 13 '26 17:06

Fiffe


Instead of using if/else, there actually exists a ternary operator in twig

Ternary Operator / Conditional operator

{{ (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

like image 29
Niket Pathak Avatar answered Jun 13 '26 18:06

Niket Pathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!