Django access the length of a list within a template

后端 未结 4 763
日久生厌
日久生厌 2020-12-28 11:49

Simple question. I have a list in my template and want to output the length of the list. Do I have to calculate this in my view and hand it over via my context?



        
相关标签:
4条回答
  • 2020-12-28 12:03

    Use list|length. | indicates that you will use a filter. The size of the list is

    {{ list|length }}
    
    0 讨论(0)
  • 2020-12-28 12:04
    {% if your_list %}
    {{ your_list|length }}
    {% endif %}
    

    Just remember that if your_list is a property it will be tigger on this line, so if you make dynamic list that is created each time you ask for it and you want to for later you will trigger it twice;

    0 讨论(0)
  • 2020-12-28 12:08

    Just a little update in case someone ends up here. As pointed in the comments, if you have a QuerySet, now it's possible to get the length with:

    {{ your_list.count }}
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-28 12:10

    Use length filter:

    {{ some_list|length }}
    
    0 讨论(0)
提交回复
热议问题