0

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?

2 Answers 2

2

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 }} 
Sign up to request clarification or add additional context in comments.

Comments

-1

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

3 Comments

This won't work, as the template will take the literal string 'factor_id' as the dictionary key, not the value of the factor_id variable.
@kbnk : can I do anything to fix this and use this method ? I don't want to create a filter for this
@Navid777 You can solve it by refactoring income and factors in some way in your view code, but otherwise you need a template filter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.