I want to traverse multiple lists within a django template in the same for loop. How do i do it?
some thinking link this:
{% for item1, item2, item3 in list1, list2 list3 %}
{{ item1 }}, {{ item2 }}, {{ item3 }}
{% endfor %}
Is something like this possible?
The syntax of the Django template language involves four constructs: {{ }} and {% %} . In this shot, we will look at how to use a for loop in Django templates. The for template in Django is commonly used to loop through lists or dictionaries, making the item being looped over available in a context variable.
There's a single Django template tag for looping: {% for %} . It uses a similar syntax to Python's for statement and provides some built-in variables that give information about where you are in the iteration. Lines 7 to 11 contain a {% for %} block, which is similar to the for keyword in Python.
You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the {% load %} tag.
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.
You have two options:
1. You define your objects so that you can access the items like parameters
for x in list:
{{x.item1}}, {{x.item2}}, {{x.item3}}
Note that you have to make up the list by combining the three lists:
lst = [{'item1': t[0], 'item2': t[1], 'item3':t[2]} for t in zip(list_a, list_b, list_c)]
2. You define your own filter
from django import template
register = template.Library()
@register.filter(name='list_iter')
def list_iter(lists):
list_a, list_b, list_c = lists
for x, y, z in zip(list_a, list_b, list_c):
yield (x, y, z)
# test the filter
for x in list_iter((list_a, list_b, list_c)):
print x
See the filter documentation
Abusing django templates:
{% for x in list_a %}
{% with forloop.counter|cut:" " as index %}
{{ x }},
{{ list_b|slice:index|last }},
{{ list_c|slice:index|last }} <br/>
{% endwith %}
{% endfor %}
But NEVER do that!!! just use zip in Your views.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With