How can I pass the values of list elements by index to the template - as the number of iterations of the loop?
How can I pass the values of list elements by index to the template - as the number of iterations of the loop?
I have a loop in the template and I would like to pass the number of iterations in the loop - as the value of the element in the list.
[10, 5, 8] - each element of the list is the required number of iterations.
list_2 = [10, 5, 8]
j = 0
i = 0
{% for len(list_1) ...number of iterations... in %}
<a>list_1[j]</a>
{% for list_2[j] ...number of iterations... in %}
<div>
{{ list_3[i] }}
i = i + 1
</div>
{% endfor %}
j = j + 1
{% endfor %}
<div>
<fieldset>
<legend>{{ form_2.name_working.label }}</legend>
{% for radio in form_2.name_working %}
<div class="myradio">
{{ radio }}
</div>
{% endfor %}
</fieldset>
</div>
If I understand correctly, you need 2 custom template filters: one to get list item by index, and another to generate range from number
# The 1st templatetag
from django import template
register = template.Library()
@register.filter
def list_item(the_list, index):
return the_list[index]
# The 2nd tmeplatetag
from django import template
register = template.Library()
@register.filter
def num_range(num):
return range(num)
These 2 files should locate in your_app/templatetags/
, with an extra __init__.py
, so that the server loads these on startup.
And then in your template
{% load list_item num_range %}
{% for j in list_1 %}
<div>{{ j }}</div>
{% for i in list_2|list_item:j|num_range %}
<div>
{{ list_3|list_item:i }}
</div>
{% endfor %}
{% endfor %}