我怎样才能做到这一点:
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]
你们有什么主意吗?
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 %}
标签下)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句