tags:

views:

216

answers:

4

Hi,

I want to see if the number of elements in an array in my Django template is greater than 1. Can i use the following syntax for doing that ?

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

Thank You

+1  A: 

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.

Ned Batchelder
+2  A: 

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

barbuza
+3  A: 

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

HardQuestions
A: 

Maybe this will be of any help ?

Checking collection sizes in Django templates is somewhat limited. The only solution that I was using, was passing another param from view to template - but to be honest, if depends from what You are trying to achieve.

zeroDivisible