Jonathan
Jonathan

Reputation: 8891

Access a dictionary element in the Django template with a variable

The situation is the following. We render a view.

return render(request, 'test.html', {'db_object': db_object, 'dict': dict }

In the template we would now like to access the dictionary with db_object.key. In python you would normally do dict[db_object.key]. In the template you could do {{ dict.some_key }} to access the value. But in the following situation you obviously can't do {{ dict.db_object.key }}

Is there a way to accomplish this?

Upvotes: 0

Views: 1700

Answers (1)

MBrizzle
MBrizzle

Reputation: 1813

This has been covered before, and the best solution I've found is to create a quick custom filter. In case that link goes dead, here's the code (which I did not write, but am providing as reference):

@register.filter 
def get_item(dictionary, key): return dictionary.get(key)

And in the template:

{{ dict|get_item:object.key }}

Of course, make sure to call load on your template tags so they're visible to the renderer.

Upvotes: 3

Related Questions