[英]How do you iterate tuple values in a dictionary for django context
I am trying to push a Django context dictionary to a template. 我正在尝试将Django上下文字典推送到模板。
I have a bunch of values for songs and created a dictionary with tuple values like so: 我有一堆歌曲的值,并创建了一个包含元组值的字典,如下所示:
songs = {'titles': ('Hello', 'Umbrella'), 'artists': ('Adele', 'Rihanna')}
How do I loop it to output: 我如何循环输出:
Hello
Adele
Umbrella
Rihanna
Or maybe I should rethink my context dictionary setup? 还是我应该重新考虑上下文词典的设置?
Do this: 做这个:
for title, artist in zip(songs['titles'], songs['artists']):
print(title)
print(artist)
print() # In Python 2, remove the parentheses
In your view: 您认为:
titles = ('Hello', 'Umbrella')
artists = ('Adele', 'Rihanna')
songs = {'titles_artists': zip(titles, artist)}
in your template: 在您的模板中:
{% for title, artist in titles_artists %}
<p>{{ title }}<br>{{ artist }}</p>
{% endfor %}
You can try rethink your context dictionary, something like: 您可以尝试重新考虑上下文字典,例如:
songs = {'artists': [
{'name': 'Adele', 'titles': ['Hello', ]},
{'name': 'Rihanna', 'titles': ['Umbrella', ]}
]
}
And in your template: 在您的模板中:
{% for artist in artists %}
{% for title in artist.titles %}
{{ title }}
{% endfor %}
{{ artist.name }}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.