Twig - 三元条件运算符

Twig - ternary conditional operator

这听起来很愚蠢,但我不知道如何在我的树枝模板中编写这个三元条件。

 {% for post in posts %}
   <div class="news_text {{ loop.index is odd ? left : right }}">
     {{ post.content }}
   </div>
 {% endfor %}

谁能告诉我什么是好的语法? :-)

您可以尝试换一种方式。 创建一个 if 并根据结果集向左或向右输出。

{% for post in posts %}    
    {% set output = "right" %}
    {% if loop.index is odd %}
        {% set output = "left" %}
    {% endif %}
    <div class="news_text {{ output }}">    
{% endfor %}

但是如果你想按照自己的方式去做,试试:

{% for post in posts %}
  <div class="news_text {{ loop.index is odd ? "left" : "right" }}">
{% endfor %}

twig

中实际上存在一个三元运算符,而不是使用if/else

三元运算符/条件运算符

{{ (isTrue) ? 'true' : 'false' }}

也支持速记语法

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Official Docs