Search code examples
djangodjango-templates

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'


Solution

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