Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing multiple lists in django template in same for loop

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?

like image 218
demos Avatar asked Jun 28 '10 13:06

demos


People also ask

How do I loop a list through a template in Django?

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.

Which Django template syntax allows to use the for loop?

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.

Which template command makes a custom template tag filter available in template?

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.

What are templates in Django?

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.


2 Answers

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

like image 156
the_void Avatar answered Oct 06 '22 01:10

the_void


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.

like image 22
petraszd Avatar answered Oct 05 '22 23:10

petraszd