Checking the number of elements in an array in a Django template

Solution 1:

As of Django 1.2; if supports boolean operations and filters, so you can write this as:

{% if myarr|length > 1 %}
<!-- printing some html here -->
{% endif %}

See the Django Project documentation for if with filters.

Solution 2:

no. but you can use django-annoying, and {% if myarr|length > 1 %} will work fine.

Solution 3:

Sad, but there is no such functionality in django's 'if' tag. There is a rumors that smarter if tag will be added in 1.2., at least it's in High priority list.

Alternatively you can use "smart_if" tag from djangosnippets.com

OR you can add your own filter (same like length_is filter) - but it's just adding more useless code :(

from django import template
register = template.Library()

def length_gt(value, arg):
    """Returns a boolean of whether the value is greater than an argument."""
    try:
        return len(value) > int(arg)
    except (ValueError, TypeError):
        return ''
length_gt.is_safe = False
register.filter(length_gt)

For more info consult django docs

Solution 4:

This is one of those powers the Django template language doesn't give you. You have a few options:

  1. Compute this value in your view, and pass it into the template in a new variable.

  2. Install an add-on library of template tags that lets you get richer comparisons, for example: http://www.djangosnippets.org/snippets/1350/

  3. Use a different templating language altogether, if you think you'll be frequently running into templating language limitations.