Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a dict by variable in Django templates?

My view code looks basically like this:

context = Context()  context['my_dict'] = {'a': 4, 'b': 8, 'c': 15, 'd': 16, 'e': 23, 'f': 42 } context['my_list'] = ['d', 'f', 'e', 'b', 'c', 'a'] 

And what I'd like to do in my Django template is this:

<ul> {% for item in my_list %}    <li>{{ item }} : {{ my_dict.item }}</li> {% endfor %}  </ul> 

And I'd like this to output:

<ul>    <li> d : 16 </li>    <li> f : 42 </li>    <li> e : 23 </li>    <li> b : 8 </li>    <li> c : 15 </li>    <li> a : 4 </li>  </ul>  

But the reference to the dict by variable name via {{ my_dict.item }} doesn't actually work. I suspect it's internally doing my_dict['item'] instead of my_dict[item]. Is there any way to work around this?

like image 687
slacy Avatar asked Jan 14 '10 19:01

slacy


People also ask

How do I access a dictionary in Django?

To access a dictionary element in a Python Django template, we can use the items property. We get the key and value pairs from choices. items and then we render them in the li element.

What is {% include %} in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What is Django template language?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

There's no builtin way to do that, you'd need to write a simple template filter to do this: http://code.djangoproject.com/ticket/3371

like image 164
Alex Gaynor Avatar answered Sep 21 '22 05:09

Alex Gaynor