如何在Django模板中引用列表中的最后一项?{ { list.-1。关键} }

时间:2023-01-10 20:22:08

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

如果我有一个变量在未知长度的上下文中;列表=[{“关键”:“A”},{“关键”:“B”},{“关键”:' 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'

如何得到最后一个对象?{ { list.0。键}用于第一个,但{list. 1}。关键} }走样;不能解析余数:'-1。主要从“value - 1. -键”

6 个解决方案

#1


51  

Thanks everyone for you help, it lead me to the realisation that I can use the with tag.

谢谢大家的帮助,这让我意识到我可以使用with标签。

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

#2


24  

Use the last template tag:

使用最后的模板标签:

{{ value|last }}

If value is the list ['a', 'b', 'c', 'd'], the output will be the string "d".

如果值是列表['a', 'b', 'c', 'd'],输出将是字符串"d"。

#3


6  

In my case I find this solution: {{object_list.last.id}} very useful on expression like this: {% url 'my-url' object_list.first.id object_list.last.id %}

在我的例子中,我找到了这个解决方案:{object_list.last。id}对于这样的表达式非常有用:{% url' my-url' object_list.first。id object_list.last。id % }

#4


1  

slice

#5


0  

without with, will be:

没有,将会:

{% set last = list|last %}
{{ last.key }}

#6


-3  

Use this piece of code in your template:

在模板中使用这段代码:

{{ list|slice:":-1".items.0.0 }}

#1


51  

Thanks everyone for you help, it lead me to the realisation that I can use the with tag.

谢谢大家的帮助,这让我意识到我可以使用with标签。

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

#2


24  

Use the last template tag:

使用最后的模板标签:

{{ value|last }}

If value is the list ['a', 'b', 'c', 'd'], the output will be the string "d".

如果值是列表['a', 'b', 'c', 'd'],输出将是字符串"d"。

#3


6  

In my case I find this solution: {{object_list.last.id}} very useful on expression like this: {% url 'my-url' object_list.first.id object_list.last.id %}

在我的例子中,我找到了这个解决方案:{object_list.last。id}对于这样的表达式非常有用:{% url' my-url' object_list.first。id object_list.last。id % }

#4


1  

slice

#5


0  

without with, will be:

没有,将会:

{% set last = list|last %}
{{ last.key }}

#6


-3  

Use this piece of code in your template:

在模板中使用这段代码:

{{ list|slice:":-1".items.0.0 }}