如何在 Django 模板中引用列表中的最后一项?{{ list.-1.key }} [英] How can reference the last item in a list in a Django template? {{ list.-1.key }}
本文介绍了如何在 Django 模板中引用列表中的最后一项?{{ list.-1.key }}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个未知长度的上下文中的变量,例如;list=[{'key':'A'},{'key':'B'},{'key':'C'}]
if I have a variable in the context of unknown length, for example;
list=[{'key':'A'},{'key':'B'},{'key':'C'}]
我怎样才能得到最后一个对象?{{ list.0.key }}
适用于第一个,但 {{ list.-1.key }}
给出;无法解析余数:'-1.key' from 'list.-1.key'
How can I get the last object? {{ list.0.key }}
works for the first, but {{ list.-1.key }}
gives;
Could not parse the remainder: '-1.key' from 'list.-1.key'
推荐答案
感谢大家的帮助,这让我意识到我可以使用 带标签.
Thanks everyone for you help, it lead me to the realisation that I can use the with tag.
{% with list|last as last %}
{{ last.key }}
{% endwith %}
这篇关于如何在 Django 模板中引用列表中的最后一项?{{ list.-1.key }}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文