views:

163

answers:

3

I'd like to use a variable as an key in a dictionary in a Django template. I can't for the life of me figure out how to do it. If I have a product with a name or ID field, and ratings dictionary with indices of the product IDs, I'd like to be able to say:

{% for product in product_list %}
     <h1>{{ ratings.product.id }}</h1>
{% endfor %}

In python this would be accomplished with a simple

ratings[product.id]

But I can't make it work in the templates. I've tried using with... no dice. Ideas?

A: 

Use the with tag to get the value of product.id into a simple identifier, then use that.

Ignacio Vazquez-Abrams
A: 

You need to prepare your data beforehand, in this case you should pass list of two-tuples to your template:

{% for product, rating in product_list %}
    <h1>{{ product.name }}</h1><p>{{ rating }}</p>
{% endfor %}
cji
Thanks cji! I was trying to avoid another object, but it doesn't really matter... it's all cached anyway.
CaptainThrowup
+1  A: 

you can do this:

{% for product in product_list %}
{% with producto.id as id_product %}
     <h1>{{ ratings.id_product  }}</h1>
{% endwith%}
{% endfor %}
diegueus9
Yeah, I already tried "with" but it didn't work. I'm not sure why, it makes perfect sense.
CaptainThrowup
Doesn't work for me either.
Mitch
what django version?
diegueus9