Django Template For Loop

Django Template For Loop

Django provides a template tag "for" to provide the for loop functionality in django templates. You can find the “for loop” syntax below.

{% for local_name in iterable_name %}  
 {{ local_name }}  
{% endfor %}

Let's talk about a real time use case, For example if you want to show all athletes data in a ordered list in HTML then using django for loop we can do as follows.

views.py

from django.shortcuts import render  

def athletes_list(request):  
  context = {"athletes": ["John Snow", "Dean Winchester", "Sam Winchester"]}  
  return render(request, "template.html", context)

template.html

 <ol>  
 {% for name in athletes %}  
 <li> {{name}}</li>  
 {% endfor %} 
 </ol>

output

 <ol>  
 <li> John Snow</li>  
 <li> Dean Winchester</li>  
 <li> Sam Winchester</li>  
 </ol>

In the above example used list data structure with the for loop. In the same way we can also use other data types like tuple, set, dict, etc.

Some times we may need to iterate the items in reverse order in this kinds of cases we "reversed"

template.html

 <ol>  
  {% for name in athletes reversed %}  
  <li> {{name}}</li>  
  {% endfor %}
 </ol>

output:

<ol>  
  <li> Sam Winchester</li>  
  <li> John Snow</li>  
  <li> Dean Winchester</li>  
</ol>

In some cases we may need to access index number of for loop then we can use "forloop.counter" like below

template.html

  {% for name in athletes %}  
   <p>{{forloop.counter}}. {{name}}</p>  
 {% endfor %} 

output:

<p> 1. Sam Winchester</p>  
 <p> 2. John Snow</p>  
 <p> 3. Dean Winchester</p>

We can use nested for loops in django templates. The for loop sets a number of variables available within the loop:

Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop surrounding the current one

Reference: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#for