如何引用Django模板列表中的最后一个项目? {{list.-1.key}} [英] How can reference the last item in a list in a Django template? {{ list.-1.key }}

查看:910
本文介绍了如何引用Django模板列表中的最后一个项目? {{list.-1.key}}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在长度不明的上下文中有一个变量,例如;

list = [{'key':'A'},{'key':' B'},{'key':'C'}]



如何获取最后一个对象? {{list.0.key}} 适用于第一个,但 {{list.-1.key}} 给出;

无法解析余数:'-1.key'from'list.-1.key'

解决方案

感谢大家帮忙,这让我意识到我可以使用使用标签

  {%with list | last as last%} 
{{last.key}}
{%endwith%}


if I have a variable in the context of unknown length, for example;
list=[{'key':'A'},{'key':'B'},{'key':'C'}]

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆