假设lst是以字符串形式表示的蔬菜的List:["cucumbers", "peppers", "tomatoes", "carrots"]。我希望用逗号加入这些单词,但我希望最后一个单词是and (出于本练习的目的,我们假设牛津逗号具有一定的容忍度),以获得以下结果:
cucumbers, peppers, tomatoes, and carrots
我该如何在Jinja2中实现这一点?我知道loop.last让我识别最后一次迭代,但不是倒数第二次迭代,这才是相关的。
发布于 2017-02-13 16:38:38
{% if loop.revindex == 2 %}或
{% if loop.revindex0 == 1 %}请参阅List of Control Structures一章中的for循环变量。
发布于 2017-09-15 06:10:13
我通过这样做获得了牛津逗号:
{% 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 %}发布于 2019-09-18 19:01:33
对于那些不想要牛津逗号的人,我用了这个:
{% 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 carrotshttps://stackoverflow.com/questions/42123896
复制相似问题