Can I access certain key values ​​in a dictionary from a django template?

Is there any get () function for this?

{% for key, value in choices.items %} <li>{{key}} - {{value}}</li> {% endfor %} 

From python, I have a get () function to get values ​​from a specific key. But I could not find an appropriate way to do this using django template tags. So I wonder if this is possible? I need to get specific values, as using loops adds a lot of new lines to the HTML source.

Or you should take care of the output inside the view before sending it to the template, which method is better?

+6
source share
6 answers

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

There is no reason to care about whitespace in HTML code; the typical end user does not have a real business in reading it, and if he is curious that he always uses the DOM viewer or runs it through an HTML decoder.

+9
source

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

 {{ choices.items.somekey }} 

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

+4
source

I think you are moving forward just to share your thoughts. you can also do it

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

or with a key, type value

 {% for key,value in dict.items %} {{key}} : {{ value }} {% endfor %} 
+3
source

If the DICT selection type is similar to {}.

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

If options.items is a DICT type.

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

Try a little example.

 # In Views.py def dict_test(request): my_little_dict = {"hi": "Hello"} .... # in Template {{my_little_dict.hi}} 
+1
source

You can specify {{ choices.key_name }} This worked for me. Just easy

0
source
 {{ choices.values }} 

This gives you a list of all the values ​​in the dictionary at the same time.

0
source

Source: https://habr.com/ru/post/911893/


All Articles