Django access the length of a list within a template

DjangoTemplates

Django Problem Overview


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

Django Solutions


Solution 1 - Django

Use length filter:

{{ some_list|length }}

Solution 2 - Django

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

{{ list|length }}

Solution 3 - Django

{% 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;

Solution 4 - Django

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRParadoxView Question on Stackoverflow
Solution 1 - DjangoK ZView Answer on Stackoverflow
Solution 2 - DjangopistacheView Answer on Stackoverflow
Solution 3 - DjangoBigRetroMikeView Answer on Stackoverflow
Solution 4 - DjangoAlvaroView Answer on Stackoverflow