在 Django 模板中使用变量作为字典键 [英] Use variable as dictionary key in Django template

查看:32
本文介绍了在 Django 模板中使用变量作为字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Django 模板中使用一个变量作为字典中的键.我一生都无法弄清楚该怎么做.如果我有一个带有名称或 ID 字段的产品,以及带有产品 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆