如何在for循环中使用Django模板点表示法

2024-04-27 17:57:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试检索字典键的值,并在页面上的Django模板中显示该值:

{% for dictkey in keys %}
    <p> {{ mydict.dictkey }} </p>
{% endfor %}

(假设'keys'和'mydict'已经在上下文中传递到模板中)

Django呈现页面,但没有字典内容(“无效的模板变量”)

我假设问题是它试图在变量dictkey]中执行mydict['dictkey']而不是mydict[实际键?一个人如何“逃避”这种行为?在

谢谢!在

更新: 根据收到的答案,我需要补充一点,我实际上是在寻找如何在for循环中实现键查找。这更能代表我的实际代码:

^{pr2}$

基本上,我有两个字典共享相同的键,所以我不能对第二个字典执行items()技巧。在


Tags: django答案代码in模板内容for字典
3条回答

来自http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

诀窍是您需要调用dict.items()来获得(key, value)对。在

请参阅this answer到一个(可能重复的)相关问题。在

它创建了一个自定义筛选器,当应用于以键作为参数的字典时,使用该键在字典上执行查找并返回结果。在

代码:

@register.filter
def lookup(d, key):
    if key not in d:
        return None
    return d[key]

用法:

^{pr2}$

注册过滤器在documentation中介绍。在

我觉得很遗憾,这种东西不是天生的。在

参见文档:http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

相关问题 更多 >