How can I check the size of a collection within a Django template?

MrDatabase picture MrDatabase · May 23, 2009 · Viewed 137.2k times · Source

I have a list in my Django template. I want to do something only if the size of the list is greater than zero.

I have tried myList|length and myList|length_is but they have not been successful.

I've searched all over and don't see any examples. How can I check this?

Answer

Alex Martelli picture Alex Martelli · May 23, 2009

See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}