Hans de Jong
Hans de Jong

Reputation: 2078

Show the dictionary key in django template

Im wondering how i could show the dictionary key itself in a django template

Example dictionary:

resources = {'coin': coin, 'grain': grain, 'iron': iron, 'stone': stone, 'wood': wood,}

Template

<b>Coin: </b>{{ upgrade.coin }}

Were i want to use the dictionary key (+some html) instead of the hard coded "Coin:"

Can anyone please help me out?

Upvotes: 7

Views: 5154

Answers (2)

macfij
macfij

Reputation: 3209

In your views, you can pass to render the whole dictionary and iterate over it in your template.

views.py

def home(request):
    resources = {'coin': coin, 'grain': grain, 'iron': iron, 'stone': stone, 'wood': wood,}
    return render(request, "home.html", {'r':resources})

home.html

{% for key,value in r.items %}
    {{ key }}
{% endfor %}

Upvotes: 3

falsetru
falsetru

Reputation: 369094

Use for tag with dict.items if you want to print all key/value pairs:

{% for key, value in resources.items %}
    <b>{{ key }}: </b>{{ value }}
{% endfor %}

Upvotes: 9

Related Questions