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?

3/28/2012 8:45:25 PM

Accepted Answer

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.

3/28/2012 9:14:50 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow