Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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

like image 831
miket Avatar asked Nov 09 '09 12:11

miket


People also ask

What does {{ this }} mean in Django?

{{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view. {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that will be placed here.

How do I find the length of a QuerySet?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.

What does {% include %} do in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


2 Answers

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.

like image 159
Rob Osborne Avatar answered Oct 06 '22 01:10

Rob Osborne


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

like image 37
Victor Kotseruba Avatar answered Oct 06 '22 00:10

Victor Kotseruba