81

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?

<p>the size of the list is {{??}}</p>

{% for element in list %}
<p>element.Name</p>
{% end for %}
bmjrowe
  • 306
  • 1
  • 2
  • 15
RParadox
  • 6,393
  • 4
  • 23
  • 33
  • possible duplicate of [How Can I Check the Size of a Collection with Django Templates?](http://stackoverflow.com/questions/902034/how-can-i-check-the-size-of-a-collection-with-django-templates) – titusfx Sep 24 '14 at 10:37

4 Answers4

170

Use length filter:

{{ some_list|length }}
K Z
  • 29,661
  • 8
  • 73
  • 78
18

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

{{ list|length }}
arulmr
  • 8,620
  • 9
  • 54
  • 69
pistache
  • 5,782
  • 1
  • 29
  • 50
9
{% 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;

BigRetroMike
  • 139
  • 1
  • 10
5

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!

Alvaro
  • 1,853
  • 18
  • 24
  • Be careful, this only works with **QuerySet** as it calls their _count()_ method. [Python List count function](https://www.geeksforgeeks.org/python-list-function-count/) takes at least 1 argument to know what to count so it won't display anything in your template. – Benbb96 Sep 25 '19 at 07:33
  • 1
    The count property only works on querysets as pointed out by @Benbb96. The template tag pointed out above by BigRetroMike works better. – Codebender May 28 '20 at 20:57