Show the dictionary key in django template

江枫思渺然 提交于 2021-02-19 02:06:36

问题


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?


回答1:


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 %}



回答2:


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 %}


来源:https://stackoverflow.com/questions/20956687/show-the-dictionary-key-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!