Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template access to nested data

This seems silly, but I don't understand how Django Templates access nested data in Contexts. I can access the values of dictionaries nested in the context data structure with the . notation -- {{ aDictionary.i_am_a_key }} works fine. But if I try to iterate over a list of keys and get their value from that same dictionary, I get nothing. So

{% for key in keys_list %}{{ aDictionary.key }}{% endfor}}

just generates blanks.

What am I missing here? Does Django not support key access to context dictionaries on the fly? Do I need to write a custom tag to do this?

EDIT

My examples assume these data structures:

aDictionary = {'i_am_a_key': 'all good', 'i_am_another_key': 'okay'}
keys_list = ['i_am_a_key', 'i_am_another_key']
like image 784
chernevik Avatar asked Dec 22 '22 07:12

chernevik


1 Answers

This is a fundamental limitation of the Django templating language.

Three solutions:

  1. Use {% for key,value in foo.items %} to get key and value.
  2. Use Jinja2 -- an almost Django-like templating system.
  3. User the expr djangosnippet to do the access math.
like image 188
Peter Rowell Avatar answered Jun 01 '23 21:06

Peter Rowell