51

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

ddaa
  • 52,890
  • 7
  • 50
  • 59
miket
  • 2,539
  • 3
  • 18
  • 6

5 Answers5

91

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.

Rob Osborne
  • 4,897
  • 4
  • 32
  • 43
  • 2
    One curious thing: in 1.6 if you use spaces like `myarr | length`, django will print it, but if you try to compare, you get an error. To compare, I had to remove the spaces. – aldux Oct 01 '14 at 21:09
  • 1
    Note that you can use the same syntax to check `formset|length` like `{% if formset|length == 1 %}` – Ehsan88 Jul 17 '20 at 16:28
7

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

4

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
  • 4,075
  • 7
  • 34
  • 39
2

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
  • 364,293
  • 75
  • 561
  • 662
0

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.

Community
  • 1
  • 1
zeroDivisible
  • 4,041
  • 8
  • 40
  • 62