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

86๐Ÿ‘

โœ…

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 %}
๐Ÿ‘คJake

47๐Ÿ‘

Use the last template tag:

{{ value|last }}

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

๐Ÿ‘คmiku

9๐Ÿ‘

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

๐Ÿ‘คHelder

6๐Ÿ‘

You can mark the last forloop by the following tags

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

and add you special desire inside the tags.

๐Ÿ‘คDavid Louda

1๐Ÿ‘

without with, will be:

{% set last = list|last %}
{{ last.key }}
๐Ÿ‘คuser2350206

0๐Ÿ‘

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 %}
๐Ÿ‘คSafiullah Khan

-3๐Ÿ‘

Use this piece of code in your template:

{{ list|slice:":-1".items.0.0 }}
๐Ÿ‘คikostia

Leave a comment