20

I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie.

{% for i,j in table, total %} 
 {{ i }} 
 {{ j }}
{% endfor %} 

or something similar?

jpic
  • 32,891
  • 5
  • 112
  • 113
mike
  • 897
  • 2
  • 10
  • 29
  • Does this answer your question? [Iterating through two lists in Django templates](https://stackoverflow.com/questions/2415865/iterating-through-two-lists-in-django-templates) – djvg May 08 '23 at 09:59

6 Answers6

45

If both lists are of the same length, you can return zipped_data = zip(table, total) as template context in your view, which produces a list of 2-valued tuples.

Example:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> zip(lst1, lst2)
[('a', 1), ('b', 2), ('c', 3)]

In your template, you can then write:

{% for i, j in zipped_data %}
    {{ i }}, {{ j }}
{% endfor %}

Also, take a look at Django's documentation about the for template tag here. It mentions all possibilities that you have for using it including nice examples.

pemistahl
  • 9,304
  • 8
  • 45
  • 75
  • this question seemed rather easy, or im rather dum. but thanks to every one that answered! – mike Feb 12 '13 at 21:00
  • 4
    @mike You are not dumb. All of us were at this point some time ago when learning about Python and Django. And Django's docs don't mention Python's `zip` function, so this question was definitely useful. I'm glad that I could help you. :) – pemistahl Feb 12 '13 at 21:02
7

For any recent visitors to this question, forloop.parentloop can mimic the zipping of two lists together:

{% for a in list_a %}{% for b in list_b %}
    {% if forloop.counter == forloop.parentloop.counter %}
        {{a}} {{b}}
    {% endif %}
{% endfor %}{% endfor %}
Melipone
  • 511
  • 5
  • 7
5

If it's just the variables i and j that you're looking at then this should work -

return render_to_response('results.html',
    {'data': zip(table, list)})

{% for i, j in data %}
    <tr>
        <td> {{ i }}: </td> <td> {{ j }} </td>
    </tr>
{% endfor %}

(credit to everyone else who answered this question)

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88
5

Use python's zip function and zip the 2 lists together.

In your view:

zip(table, list)

In your template, you can iterate this like a simple list, and use the .0 and .1 properties to access the data from table and list, respectively.

Jordan
  • 31,971
  • 6
  • 56
  • 67
1

Rather than using a dictionary (which does not guarantee any kind of sorting), use the python zip function on the two lists and pass it to the template.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
1

You'll have to do this in the view - use the builtin zip function to make a list of tuples, then iterate over it in the template.

Template logic is purposely simple, anything even slightly complex should be done in the view.

Ben
  • 6,687
  • 2
  • 33
  • 46