1

How can I do this:

x = 'id_1'
d = {'id_1':1, 'id_2':2}
print d[x]    

in django template, I've tried this:

{% for field in form %}
    <tr>
        <th><label for="{{ field.auto_id }}" >{{ field.label }} </label></th>
        <td>Some text from dict: {{context_dict.field.auto_id}} {{field}}</td>
     </tr>
{% endfor %}

in context_dict.field.auto_id, I need context_dict.[field.auto_id]

Do you guys have any ideas?

Thomas Jerkson
  • 229
  • 1
  • 2
  • 7
  • 1
    Possible duplicate of [Use variable as dictionary key in Django template](http://stackoverflow.com/questions/2894365/use-variable-as-dictionary-key-in-django-template) – falsetru Oct 17 '15 at 18:55

1 Answers1

1

Create a python package called templatetags in your app folder, then create a file called something like custom_tags.py, and in that file put:

from django import template

register = template.Library()

@register.filter()
def lookup(the_dict, key):
    return the_dict.get(key, '')

so now you can lookup the value by something like:

{{ context_dict|lookup:key }}

Note: Make sure to load the template tags into your template via {% load custom_tags %} (place it at the top of the file, but under any {% extends %} tags.

Hybrid
  • 6,741
  • 3
  • 25
  • 45