Checking the number of elements in an array in a Django template
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
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.
no. but you can use django-annoying, and {% if myarr|length > 1 %}
will work fine.
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
This is one of those powers the Django template language doesn't give you. You have a few options:
Compute this value in your view, and pass it into the template in a new variable.
Install an add-on library of template tags that lets you get richer comparisons, for example: http://www.djangosnippets.org/snippets/1350/
Use a different templating language altogether, if you think you'll be frequently running into templating language limitations.
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.
精彩评论