Accessing a dict by variable in Django templates?

Viewed 33033

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?

4 Answers

Here's a usage case of the suggested answer.

In this example, I created a generic template for outputting tabular data from a view. Meta data about the columns is held in context["columnMeta"].

Since this is a dictionary, i cannot rely on the keys to output the columns in order, so i have the keys in a separate list for this.

In my view.py:


c["columns"] = ["full_name","age"]
c["columnMeta"] = {"age":{},"full_name":{"label":"name"}}

In my templatetags file:


@register.filter
def getitem ( item, string ):
  return item.get(string,'')

In my template:

<tr>
<!-- iterate columns in order specified -->
{% for key in columns %}
<th>
 <span class="column-title">
    <!-- look label in meta dict.  If not found, use the column key -->
   {{columnMeta|getitem:key|getitem:"label"|default:key}}
  </span>
</th>
{% endfor %}</tr>
Related