在Django模板中使用变量作为字典键 [英] Use variable as dictionary key in Django template
本文介绍了在Django模板中使用变量作为字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Django模板的字典中使用变量作为键。我不能为我的生活找出如何做到这一点。如果我有一个名称或ID字段的产品,以及带有产品编号索引的评分字典,我可以说:
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 %}
在python中,这将通过一个简单的
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?
推荐答案
您需要事先准备好您的数据,在这种情况下,您应该将两个元组的列表传递给您的模板:
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 %}
这篇关于在Django模板中使用变量作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文