Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django counter in loop to index list

Tags:

python

django

I'm passing two lists to a template. Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list. My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

like image 840
JPC Avatar asked Jan 19 '11 03:01

JPC


2 Answers

You can't. The simple way is to preprocess you data in a zipped list, like this

In your view

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)

Then in you template :

{% for x, y in zipped %}
    {{ x }} - {{ y }}
{% endfor %}
like image 78
Xavier Barbosa Avatar answered Sep 19 '22 18:09

Xavier Barbosa


To access an iterable using a forloop counter I've coded the following very simple filter:

from django import template

register = template.Library()

@register.filter
def index(sequence, position):
    return sequence[position]

And then I can use it at my templates as (don't forget to load it):

{% for item in iterable1 %}
  {{ iterable2|index:forloop.counter0 }}
{% endfor %}

Hope this helps someone else!

like image 20
Caumons Avatar answered Sep 21 '22 18:09

Caumons