0

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?

Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • 2
    Why are you passing `dict`? You have access to your context dictionary in the template and you just need to do `{{ db_object.key }}`..? Or am I missing the point? – Henrik Andersson Aug 12 '14 at 14:19
  • Cant you use the `.items`syntax? http://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template – j-i-l Aug 12 '14 at 14:23

1 Answers1

3

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.

Community
  • 1
  • 1
MBrizzle
  • 1,783
  • 1
  • 18
  • 31