简体   繁体   中英

How to access a dictionary element in django template?

I have a dictionary named income in a django template, I also have a list named factors in my template and I want something like this :

{% for factor in factors%}
<div> {{ income[factor.id] }} </div>
{% endfor %}

but {{ income[factor.id] }} is wrong, how can I do something like this?

You could write a template tag like so:

@register.filter
def get_value(d, key):
    return d.get(key)

and use it like so:

{{ income|get_value:factor.id }}

Edit: as pointed out by @kbnk, I was mistaken and this does not work.

If you don't want to create a filter, you can try the following:

{% for factor in factors %}
    {% with factor_id=factor.id %}
        <div> {{ income.factor_id] }} </div>
    {% endwith %}
{% endfor %}

This works, because you can do a dictionary-type lookout in django templates. Checkout the django template docs for more details: https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM