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

后端 未结 6 1790
星月不相逢
星月不相逢 2021-01-01 08:33

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 ob

相关标签:
6条回答
  • 2021-01-01 09:12

    without with, will be:

    {% set last = list|last %}
    {{ last.key }}
    
    0 讨论(0)
  • 2021-01-01 09:16

    Use this piece of code in your template:

    {{ list|slice:":-1".items.0.0 }}
    
    0 讨论(0)
  • 2021-01-01 09:24

    You can mark the last forloop by the following tags

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

    and add you special desire inside the tags.

    0 讨论(0)
  • 2021-01-01 09:28

    Use the last template tag:

    {{ value|last }}
    

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

    0 讨论(0)
  • 2021-01-01 09:34

    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 %}
    
    0 讨论(0)
  • 2021-01-01 09:38

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

    0 讨论(0)
提交回复
热议问题