Jake
Jake

Reputation: 13141

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'

Upvotes: 51

Views: 46375

Answers (7)

Jake
Jake

Reputation: 13141

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

Upvotes: 88

Safiullah Khan
Safiullah Khan

Reputation: 11

It worked for my by simply counting the number of records inside the views.py file using the built in function count() and then check if the forloop.counter != total_count then add and


{% if forloop.counter != total_jobs %}
    <hr>
{% endif %}

Upvotes: 1

David Louda
David Louda

Reputation: 577

You can mark the last forloop by the following tags

{% if forloop.last %} ... {% endif %}

and add you special desire inside the tags.

Upvotes: 7

user2350206
user2350206

Reputation: 185

without with, will be:

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

Upvotes: 1

Helder
Helder

Reputation: 91

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

Upvotes: 9

ikostia
ikostia

Reputation: 7587

Use this piece of code in your template:

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

Upvotes: -3

miku
miku

Reputation: 188054

Use the last template tag:

{{ value|last }}

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

Upvotes: 48

Related Questions