Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable as dictionary key in Django template

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?

like image 989
CaptainThrowup Avatar asked May 24 '10 01:05

CaptainThrowup


2 Answers

Create a template tag like this (in yourproject/templatetags):

@register.filter def keyvalue(dict, key):         return dict[key] 

Usage:

{{dictionary|keyvalue:key_variable}} 
like image 83
eviltnan Avatar answered Sep 19 '22 20:09

eviltnan


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 %} 
like image 32
cji Avatar answered Sep 20 '22 20:09

cji