在 Jinja2 迭代中获取倒数第二个元素



lst是用字符串表示的蔬菜List["cucumbers", "peppers", "tomatoes", "carrots"] .我希望用逗号连接它们,除了我希望最后一个是单词and(出于本练习的目的,让我们假设牛津逗号的度容差(,得到以下内容:

cucumbers, peppers, tomatoes, and carrots

我将如何在Jinja2中实现这一目标?我知道loop.last让我确定最后一个,但不是倒数第二个迭代,这是相关的。

{% if loop.revindex == 2 %}

{% if loop.revindex0 == 1 %}

请参阅"控制结构列表"一章中的 for 循环变量。

我通过这样做实现了牛津逗号:

{% for label in post.labels %}
    <li><a href="/labels/{{label}}">{{label}}</a>
    {% if not loop.last and loop.length > 2%}, {%endif%}
    {% if loop.revindex0 == 1 %} and{%endif%}</li>
{% endfor %}

对于那些不想要牛津逗号的人,我使用了这个:

{% for name in my_list %}
  {{ name }}
  {%- if loop.length > 1 and not loop.last -%}
    {%- if loop.revindex0 == 1 %} and {% else %}, {% endif %}
  {% endif %}
{% endfor %}

输出如下内容:

cucumbers, peppers, tomatoes and carrots

最新更新