6

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?

Hans de Jong
  • 1,870
  • 6
  • 33
  • 53

2 Answers2

9

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 %}
falsetru
  • 336,967
  • 57
  • 673
  • 597
3

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 %}
macfij
  • 2,973
  • 1
  • 18
  • 23
  • Thanks, in view i was already using render, didn't realize you could do it with key + value in the for loop, thought you only could use the value – Hans de Jong Jan 06 '14 at 18:42