Reputation: 149
I have this dictionary:-
a = {'title': ['Turning a MacBook into a Touchscreen with $1 of Hardware (2018)', 'Supercentenarians are concentrated into regions with no birth certificates', 'Open list of GDPR fines so far'], 'url': ['https://www.anishathalye.com/2018/04/03/macbook-touchscreen/', 'https://www.biorxiv.org/content/10.1101/704080v1', 'https://github.com/lknik/gdpr/blob/master/fines/README.md'], 'type': ['story', 'story', 'story'], 'n': [0, 1, 2]}
I passed it into the template. Now, what I want is to get the first 'title' along with the 'type', with its 'url'. I tried the following code:-
<ul>
{% for i in n %}
<br/>
{{i}}
<li>{{title.i}}</li><br/>
<li>{{url.i}}</li>
{%endfor%}
But couldn't get the desired output.
My desired output is:-
Title: Turning a MacBook into a Touchscreen with $1 of Hardware (2018)
URL: https://www.anishathalye.com/2018/04/03/macbook-touchscreen/
TYPE: story
In this way a continuous list of Titles followed by url and type.
The output I get is a blank screen.
Please help me out.
Upvotes: 0
Views: 50
Reputation: 518
I wouldn't recommend your context like that though,
but if you don't want change it, u can use custom simple filters.
from django import template
register = template.Library()
@register.filter
def index(my_list, idx):
return my_list[idx]
then in your template (don't forget to load it first)
{% for item in title %}
Title: {{ item }}
URL: {{ url|index:forloop.counter0 }}
Type: {{ type|index:forloop.counter0 }}
{% endfor %}
I recommend this way, it more be simple if you use zip in your views
title = ['Turning a MacBook into a Touchscreen with $1 of Hardware (2018)', 'Supercentenarians are concentrated into regions with no birth certificates', 'Open list of GDPR fines so far']
url = ['https://www.anishathalye.com/2018/04/03/macbook-touchscreen/', 'https://www.biorxiv.org/content/10.1101/704080v1', 'https://github.com/lknik/gdpr/blob/master/fines/README.md']
type = ['story', 'story', 'story']
zipped = zip(title, url, type)
a = {'zipped': zipped}
then in your template
{% for title, url, type in zipped %}
Title: {{ title }}
URL: {{ url }}
Type: {{ type }}
{% endfor %}
or another way, use list of dictionaries instead
my list = [
{'title': 'Turning a MacBook into a Touchscreen with $1 of Hardware (2018)', 'url': 'https://www.anishathalye.com/2018/04/03/macbook-touchscreen/', 'type':'story'},
{'title': '...', 'url': '...', 'type': 'story'},
{'title': '...', 'url': '...', 'type': 'story'}
]
a = {'my_list': my_list}
then iterate it with:
{% for item in my_list %}
Title: {{ item.title}}
URL: {{ item.url}}
Type: {{ item.type }}
{% endfor %}
Upvotes: 1
Reputation: 10873
How about something like this:
<ul>
{% for key, values in a.items %}
{% if key != 'n' %}
<br/>
<li>{{ key }}: {{ values.0}}</li>
{% endif %}
{% endfor %}
</ul>
Upvotes: 0