views:

493

answers:

3

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

I have tried myList|length and myList|length_is but have not been successful. I've searched all over and don't see any examples.

+3  A: 

A list is considered to be False if it has no elements, so you can do something like this:

{% if mylist %}
    <p>I have a list!</p>
{% else %}
    <p>I don't have a list!</p>
{% endif %}
mipadi
+4  A: 

See http://www.djangoproject.com/documentation/0.95/templates/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}
Alex Martelli
+4  A: 

If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

{% for athlete in athlete_list %}
  ...
{% empty %}
  No athletes
{% endfor %}

Useful when the something that you want to do involves iterating over a non-empty list.

Dave W. Smith