Can I access specific key values in dictionary from django template?

后端 未结 6 1383
独厮守ぢ
独厮守ぢ 2021-01-05 16:20

Is there any get() function for this instead?

{% for key, value in choices.items %} 
  
  • {{key}} - {{value}}
  • {% endfor %}
    <
    相关标签:
    6条回答
    • 2021-01-05 17:09

      You can use {{ choices.items.key }} to access a specific dict element.

      There is no reason to care about whitespace in the HTML code though; the typical end-user has no real business in reading it and if he's curious he an always use a DOM viewer or run it through a HTML beautifier.

      0 讨论(0)
    • 2021-01-05 17:09

      If you want a specific value, just add it to the dotted-path:

      {{ choices.items.somekey }}
      

      will get you the value of choices.items['somekey'] if choices.items is a dict.

      0 讨论(0)
    • 2021-01-05 17:10
      {{ choices.values }}
      

      This gives you a list of all the values in the dictionary at once.

      0 讨论(0)
    • 2021-01-05 17:11

      If choices type is DICT like {}.

      {{choices.somekey|default:""}}
      

      If choices.items is DICT type.

      {{choices.items.somekey|default:""}}
      

      Try See little example.

      # In Views.py
      def dict_test(request):
          my_little_dict = {"hi": "Hello"} 
          ....
      # in Template
      {{my_little_dict.hi}}
      
      0 讨论(0)
    • 2021-01-05 17:11

      You can specify as {{ choices.key_name }} It worked for me. Just simple

      0 讨论(0)
    • 2021-01-05 17:12

      I think you are way advance now, just to share my point. you could do this way as well

      {% for value in dict %} 
          {{value}}                                                                   
      {% endfor %}
      

      or with key, value like

      {% for key,value in dict.items %}
          {{key}} : {{ value }}
      {% endfor %}
      
      0 讨论(0)
    提交回复
    热议问题