Reputation: 888
So I'm loading a dictionary to HTML but I'm having some trouble getting the second_value
from the dictionary ({'first_value': 'second_value'}
).
The dictionary I'm parsing is this:
{1: 'Bayer', 2: 'Celgene Europe Limited', 3: 'Celgene Europe Limited'}
My code inside HTML:
{% for x in drugs %}
<a href="{{ x }}"><li>{{ drugs.x }}</li></a>
{% endfor %}
And what is displaying in the HTML is:
<ul style="text-decoration: none; color: black;">
<a href="1"><li></li></a>
<a href="2"><li></li></a>
<a href="3"><li></li></a>
</ul>
What is supposed to happen is the number to be displayed in the href
and the drug name to be displayed inside the <li></li>
tags.
For example:
<a href="1"><li>Bayer</li></a>
Upvotes: 0
Views: 51
Reputation: 10920
Change your HTML template to:
{% for key, val in drugs.items %}
<li><a href="{{ key }}">{{ val }}</a></li>
{% endfor %}
When looping through a dict, the key and corresponding value can be retrieved at the same time using the dict's items()
method.
Note that a <li>
element cannot be the child of an <a>
element (reference). I have fixed this issue by moving your <a>
elements inside the <li>
elements.
Upvotes: 1