(Comments)
Django templates give us a little control over the flow of rendering. for
loop is often used in the Django templates it often satisfies the needs to iterate over lists or tuples. For example, a queryset with multiple models can be iterated over in the templates with the for loop:
context = { 'movies': Movie.objects.all()[:10]}
The above dictionary sets the object movies
in to the template's context, it can be iterated over as:
{% for movie in movies %} <h3>{{movie.name}}</h3> {% endfor %}
The for loop in the template satisfies our needs here. But let us say we need to iterate for some n times, how do you achieve that? There are multiple methods to do this.
range
template filterIn this method we create a template tilter that takes an integer argument and returns a list of integers in the range as follows:
from django import template register = template.Library() @register.filter() def range(min=5): return range(min)
We can use this in the template as follows:
{% for value in 5|range:10 %} {{ value }} {% endfor %}
center
template filterThe center filter takes a value and aligns it to center in a field of a given width. For example,
{{ "Django"|center:"10" }}
will result in " Django "
A string in Python is iterable i.e., it can be iterated over using a for loop. For example,
for ch in 'django': print(ch)
would result in
d j a n g o
This concept can be used to make the for loop in django to run exactly the number of times we want with the code given below:
{% with ''|center:10 as range %} {% for _ in range %} {{ 'Hello' }} {% endfor %} {% endwith %}
We have first used with
to assign the result of center
tag to a string range
. We then use the for
loop to iterate over the range
string (remember, string is an iterable). The number 10
in the above code can be replaced with a variable.
We develop web applications to our customers using python/django/angular.
Contact us at hello@cowhite.com
Comments