2017-02-08 63 views
0

lst爲表示爲字符串的蔬菜的List["cucumbers", "peppers", "tomatoes", "carrots"]。我希望用逗號加入這些,但我希望最後一個待字and,而不是(在這個練習的目的,讓我們假設一個牛津逗號度公差),得到如下:在Jinja2迭代中獲取倒數第二個元素

cucumbers, peppers, tomatoes, and carrots

我該如何去完成Jinja2?我知道loop.last讓我確定最後一次,但不是倒數第二次迭代,這是相關的。

+1

爲什麼不處理在普通的Python列表和使這個容易 –

+1

如果你只是需要把「和」字在裏面,那麼爲什麼不直接使用'loop.last'?把「和」放在單詞的前面,而不是放在單詞後面。 – coralvanda

回答

0

我已經這樣做達到了牛津逗號:

{% 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 %} 

您可以檢查我的博客上test page結果。這也適用於有兩個或更少的標籤爲seen here職位上我的博客

相關問題