Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django templates loops

Tags:

python

django

Can I loop through two arrays/lists in django templates simultaneously?

Something like this:

# views.py

a = [{'a':'apple','b':'banana','c':'clementine'},
     {'a':'aunt','b':'brother','c':'cousin'},
     {'a':'ant','b':'bat','c':'cat'}]
b = [{'d':'dave','f':'fred'},
     {'d':'dason','f':'ford'},
     {'d':'dance','f':'flamenco']

# something.html

{% for x, y in a and b %}
    {{ x.a }},{{ x.c }}<br>
    {{ y.f }}
{% endfor %}
like image 735
Robert Johnstone Avatar asked Apr 24 '26 18:04

Robert Johnstone


1 Answers

You can zip the two lists in your view, then iterate through the resulting list in your template.

# views.py
ab = zip(a,b)

# template
{% for x,y in ab %}
    {{ x.a }},{{ x.c }}<br>
    {{ y.f }}
{% endfor %}
like image 128
Alasdair Avatar answered Apr 26 '26 06:04

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!