【问题标题】:Django dict key in template模板中的 Django dict 键
【发布时间】:2016-01-16 08:59:35
【问题描述】:

我该怎么做:

x = 'id_1'
d = {'id_1':1, 'id_2':2}
print d[x]    

在 django 模板中,我试过这个:

{% for field in form %}
    <tr>
        <th><label for="{{ field.auto_id }}" >{{ field.label }} </label></th>
        <td>Some text from dict: {{context_dict.field.auto_id}} {{field}}</td>
     </tr>
{% endfor %}

在 context_dict.field.auto_id 中,我需要 context_dict.[field.auto_id]

你们有什么想法吗?

【问题讨论】:

标签: django templates


【解决方案1】:

在您的应用文件夹中创建一个名为templatetags 的python 包,然后创建一个名为custom_tags.py 之类的文件,并在该文件中放置:

from django import template

register = template.Library()

@register.filter()
def lookup(the_dict, key):
    return the_dict.get(key, '')

所以现在您可以通过以下方式查找值:

{{ context_dict|lookup:key }}

注意:确保通过{% load custom_tags %} 将模板标签加载到模板中(将其放在文件顶部,但在任何{% extends %} 标签下。

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 2019-01-08
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    相关资源
    最近更新 更多