Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can reference the last item in a list in a Django template? {{ list.-1.key }}

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'

like image 989
Jake Avatar asked Jan 19 '11 00:01

Jake


People also ask

What does {{ this }} mean in Django?

What does {{ name }} this mean in Django Templates? Django. It will be displayed as name in HTML. The name will be replaced with values of Python variable. {{ name }} will be the output.

What is Autoescape in Django template?

autoescape. Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.


2 Answers

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 %} 
like image 70
Jake Avatar answered Sep 18 '22 00:09

Jake


Use the last template tag:

{{ value|last }} 

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

like image 22
miku Avatar answered Sep 19 '22 00:09

miku