Jordan Messina
Jordan Messina

Reputation: 1531

Django dictionary in templates: Grab key from another objects attribute

I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so:

    {% for implementation in implementations %}
        {{ number_devices.implementation.id }}
    {% endfor %}

Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like:

{{ number_devices.(implementation.id) }}

because I get a parse error. How do I get around this annoyance in Django templates?

Thanks for any help!

Upvotes: 2

Views: 2185

Answers (1)

zovision
zovision

Reputation: 942

A workaround could be using the keys from number_devices and check in the for loop if it is equal to the key provided by number_devices.

{% for key in number_devices.keys %}
    {% for implementation in implementations %}
        {% ifequal key implementation.id %} you got it {% endifequal %}
    {% endfor %}
{% endfor %}

Seems a bit ugly, but should work.

Upvotes: 1

Related Questions