Cap*_*wup 55 django django-templates
我想在Django模板中使用变量作为字典中的键.我不能为我的生活弄明白该怎么做.如果我有一个带有名称或ID字段的产品,以及带有产品ID索引的评级字典,我希望能够说:
{% for product in product_list %}
<h1>{{ ratings.product.id }}</h1>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
在python中,这将通过简单的方式完成
ratings[product.id]
Run Code Online (Sandbox Code Playgroud)
但我不能让它在模板中工作.我试过用...没有骰子.想法?
evi*_*nan 83
像这样创建一个模板标签(在你的项目/模板标签中):
@register.filter
def keyvalue(dict, key):
return dict[key]
Run Code Online (Sandbox Code Playgroud)
用法:
{{dictionary|keyvalue:key_variable}}
Run Code Online (Sandbox Code Playgroud)
cji*_*cji 20
您需要事先准备好数据,在这种情况下,您应该将两元组列表传递给您的模板:
{% for product, rating in product_list %}
<h1>{{ product.name }}</h1><p>{{ rating }}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
pod*_*mok 14
有一个非常脏的解决方案:
<div>We need d[{{ k }}]</div>
<div>So here it is:
{% for key, value in d.items %}
{% if k == key %}
{{ value }}
{% endif %}
{% endfor %}
</div>
Run Code Online (Sandbox Code Playgroud)
在eviltnan的答案的基础上,如果key不是关键的话,他的过滤器会引发异常dict.
过滤器不应该引发异常,但应该优雅地失败.这是一个更健壮/完整的答案:
@register.filter
def keyvalue(dict, key):
try:
return dict[key]
except KeyError:
return ''
Run Code Online (Sandbox Code Playgroud)
基本上,这将与dict.get(key, '')Python代码中的相同,如果您不想包含try/except块,也可以这样编写,尽管它更明确.
| 归档时间: |
|
| 查看次数: |
36809 次 |
| 最近记录: |