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 %}
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 %}
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/custom_tags.py
" (and empty "__init__.py
" in the same folder):
from django import template
register = template.Library()
@register.filter(name='get_range')
def get_range(number):
return range(number)
@register.filter(name='get_from_dict')
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 %}