For loop with range in django template


How can I make a for loop with range function in django template?
I want to search in three lists by using this structure.

I tried this and it didn’t work:

{% for i in range(number) %}
    {{ my_list.i }}
{% endfor %}
Asked By: mhn



You cannot simply use use Pythonic round brackets inside curly brackets. Also, it’s not that simple to get from dict using variable.
You can try creating a custom template tags.

Create file in your app: "your_project/your_app/templatetags/" (and empty "" in the same folder):

from django import template

register = template.Library()

def get_range(number):
    return range(number)

def get_from_dict(my_dict, i):
    return my_dict.get(i, None)

And then in template:

{% load custom_tags %}

{% for i in number|get_range %}
    {{ my_list|get_from_dict:i }}
{% endfor %}
Answered By: NixonSparrow