I'm developing with Django. The output data is passed to the html page as follows:
def page(request):
data = { 'name':[
'nameOne',
'nameTwo',
'nameThree'
],
'id':[
'1',
'2',
'3'
]
}
return render( request, "mainpageapp/page.html", data)
I would like to see a link with text name and value id
<a href="/{{id}}">{{name}}</a>
At the moment I can only output one element in the for loop
{% for el in name %}
<a href="/{{el}}">{{el}}</a><br>
{% endfor %}
Is it possible to display two dictionary elements in one forloop? Or some other way to implement this?
Zip the two into a single iterable:
def page(request):
name = ['nameOne', 'nameTwo', 'nameThree']
ids = ['1', '2', '3']
data = zip(ids, name)
context = {'data': data}
return render(request, 'mainpageapp/page.html', context)
in the template, we then enumerate with:
{% for pk, name in data %}
<a href="/{{ pk }}">{{ name }}</a><br>
{% endfor %}
Note: Please do not name a variable
id
, it overrides the reference to theid
builtin function [Python-doc]. Use for exampleids
.