Noel Llevares
Noel Llevares

Reputation: 16037

Django templating - accessing dictionary value using a template variable

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.

Upvotes: 0

Views: 134

Answers (1)

richsilv
richsilv

Reputation: 8013

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.

Upvotes: 2

Related Questions