0

This is the data coming from my views.py:

gradebook_data = {
    'G5A': [...],
    'G5B': [...],
    ...
}

sections = [
    ('G5A': '5-Einstein'),
    ('G5B': '5-Bohr'),
    ...
]

In my template, I want to iterate the sections and display gradebook data inside a for loop like this...

{% for code, section in sections %}
    <td>{{ gradebook_data.code }}</td>
{% endfor %}

This doesn't work since in Django it tries to do a dictionary lookup for gradebook_data['code'] when what I want to do is to get gradebook_data['G5A'].

Does anybody know a workaround or can point to my mistake? I have spent a whole day just for this already.

This was quite easy to do with PHP's Twig templating library.

Noel Llevares
  • 15,018
  • 3
  • 57
  • 81

1 Answers1

2

If you're using the Django templating system you can register a custom filter, which has been documented several times on SO for exactly this purpose. For example, here.

Community
  • 1
  • 1
richsilv
  • 7,993
  • 1
  • 23
  • 29
  • I've thought about making my own filter. I was hoping however, that there is a better way or easier since this is a very common use-case. – Noel Llevares Jan 13 '14 at 21:15
  • Agreed, but it's really pretty easy if you're comfortable with working in Django, and once you've done it once the next time will be easy... – richsilv Jan 13 '14 at 21:16
  • @dashmug in the view function you're really supposed to massage the data more into the form that you later want to consume in the template – Anentropic Jan 13 '14 at 21:16
  • @Anentropic After a lot of researching, that's what I realized. Just felt that it added more complexity. In my case, can you suggest a better structure for the `gradebook_data` above? – Noel Llevares Jan 13 '14 at 21:20
  • 2
    @dashmug why not combine them into a single data structure eg `gradebook_data = {'G5A': ('5-Einstein', [...]), ...}` – Anentropic Jan 13 '14 at 21:23
  • @Anentropic Yes, I guess I have no choice. I wanted to use DRY and not do further massaging but I guess this is the only way. – Noel Llevares Jan 13 '14 at 22:03
  • Templates should be pretty stupid. Programming logic should always be in your view. – mawimawi Jan 13 '14 at 22:33