Reputation: 13141
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
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
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
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
Reputation: 185
without with, will be:
{% set last = list|last %}
{{ last.key }}
Upvotes: 1
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
Reputation: 7587
Use this piece of code in your template:
{{ list|slice:":-1".items.0.0 }}
Upvotes: -3