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开发者_StackOverflow;
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 %}
Use the last
template tag:
{{ value|last }}
If value is the list
['a', 'b', 'c', 'd']
, the output will be the string"d"
.
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 %}
You can mark the last forloop by the following tags
{% if forloop.last %} ... {% endif %}
and add you special desire inside the tags.
without with, will be:
{% set last = list|last %}
{{ last.key }}
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 %}
Use this piece of code in your template:
{{ list|slice:":-1".items.0.0 }}
精彩评论