Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any get() function for this instead?

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

From python I have the get() function to get values from a specific key. But I couldn't find a corresponding way to do that with django template tags. So I wonder is it possible? I need to get specific values since using loops adds a lot of new lines in the html source.

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

like image 758
starcorn Avatar asked Mar 28 '12 20:03

starcorn


People also ask

Can we access keys using values in dictionary?

We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.

How would you retrieve a value for a key in a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.


2 Answers

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.

like image 22
Amber Avatar answered Sep 29 '22 20:09

Amber


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.

like image 139
ThiefMaster Avatar answered Sep 29 '22 18:09

ThiefMaster