Reputation: 47
I am trying to push a Django context dictionary to a template.
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?
Upvotes: 0
Views: 96
Reputation: 246
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 %}
Upvotes: 0
Reputation: 20346
Do this:
for title, artist in zip(songs['titles'], songs['artists']):
print(title)
print(artist)
print() # In Python 2, remove the parentheses
Upvotes: 1