Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of python "for in" loop in Django template

I'm trying to iterate list in django template. In python it looks like below and it works:

l=[lots ot touples]
for li in range(len(l)):
    print(l[li])

but in django template it does not work. My question is : what is simpliest equivalent of iterating list in django template ?

My django template:

<html>
<body>
{% for w in l %}
  <li>{{ w }}</li>
{% endfor %}
</body>
</html>

Thank you in advance

P.S. I have added touples to list to show exactly what is the problem Another one PS

Output of www site ( i'm displaying unread emails form gmail) looks like below:

('From1', 'subject1', 'Thu, 12 Nov 2015 09:46:34 +0100')
('From2', 'subject2', 'Thu, 12 Nov 2015 13:48:58 +0100')
('From3', 'subject3', 'Thu, 12 Nov 2015 14:12:34 +0100')

I want every item in list assign to touple. What i'm trying to do is to assign touple , for instance:

touple1 = ('From1', 'subject1', 'Thu, 12 Nov 2015 09:46:34 +0100')

so i can later call 'from', 'subject' or 'date'

regards

Maybe i will show it in another way to make it more clear: for loop to iterate through the email messages (list of touples )

email1 = list[1]     //touple
email2 = list[2]     //touple

(...)

from1 = email1[0]
subject1 = email1[1]
date1 = email1[3]

and so on.

Solved. Thank you all for help. Every solution was for me helpfull. I would like to mark two answers ( if it possbile ) as a very usefull for me showing different way to solve same problem. I would like to mention that every help was very usefull for me. Do you mind if i will mark as correct answers Alasdair and Noah answer ( dunno how many I can mark) ?

like image 672
admfotad Avatar asked Jan 17 '26 22:01

admfotad


1 Answers

Given the following list of tuples:

emails = [
    ('From1', 'subject1', 'Thu, 12 Nov 2015 09:46:34 +0100')
    ('From2', 'subject2', 'Thu, 12 Nov 2015 13:48:58 +0100')
    ('From3', 'subject3', 'Thu, 12 Nov 2015 14:12:34 +0100')
]

You can loop through the tuples, and use .0 or .2 to access the elements by index:

{% for email in emails %}
{{ email.0 }} - {{ email.1 }} - {{ email.2 }}
{% endfor %}

Or, you can unpack the tuple variables:

{% for from, subject, date in emails %}
{{ from }} - {{ subject }} - {{ date }}
{% endfor %}

As an aside, your Python code is not very pythonic. Instead of looping over a range,

emails = [...]
for li in range(len(emails)):
print(emails[li])

you can loop over the list directly

for email in emails:
    print(emails)

You can do the same unpacking as in the Django template.

for from, sender, date in emails:
    print(from, sender, date)
like image 182
Alasdair Avatar answered Jan 20 '26 23:01

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!