Django templates help you work with various python data structures. Sometimes you may need to get a count of number of elements in a list in Django Template. For example, you may want to execute a certain block of code if the list has more than specific number of elements. Otherwise, execute another block of code. In this article, we will learn how to get length of list in Django Template.
How to get length of list in Django Template
Here are the steps to get length of list in Django Template. Let us say you pass a list called products from a view to Django Template. Let us say you want to execute a block of code if the products list has more than zero elements.
You can easily get the length of list in Django Template using length filter, as shown below. It is a pre-built filter available in most Django versions and you do not need to define it separately.
{{ products|length }}
In the above code, if products list has 3 elements then the above expression will evaluate to 3 in your Django template.
Here is an example to execute certain block of code if there are more than zero items in products list.
{% if products|length >0 %} Number of products: {{ products|length }} {% else %} No products. {% endif %}
Alternatively, you can also use the following code block.
{% if products %} Number of products: {{ products|length }} {% else %} No products. {% endif %}
In both the above code the Django template displays number of products if the list has more than zero items, else it displays that there are no products.
Also read:
Difference Between df and du
How to Create Startup Disk in Ubuntu
How to Install Fail2Ban in Docker
Disk Utilities in Linux
How to Return Multiple Values in Python Function
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.