对于 Django 模板中的循环未处理



我创建了一个字典,并将其传递给我的Django模板:

my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
t = get_template('my_site.html')
html = t.render(my_dict)
print(html)
return HttpResponse(html)

我的 Django 模板看起来像这样:

<html>
<body>
Out of Dictionary <div>
{% for key in my_dict %}
<span>{{ key }}</span>
{% endfor %} 
</div>
After dictionary    
</body>
</html>

我在浏览器中的输出如下所示: 出字典 字典后

HTML 如下所示:

<html>
<body>
Out of Dictionary <div>
</div>
After dictionary
</body>
</html>

我还尝试了以下方法来识别字典:

{% for key in my_dict %}
{% for key in my_dict.items %}
{% for key, value in my_dict.items %}
{% for (key, value) in my_dict.items %}
my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
t = get_template('my_site.html')
html = t.render(my_dict)

您的上下文有两个键:boohi。您可以在模板中按如下方式访问它们:

{{ boo }}, {{ hi }}

如果要在模板中使用mydict,请将该字典嵌套在上下文字典中:

my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}}
context = {'my_dict': my_dict}
t = get_template('my_site.html')
html = t.render(context)

然后,您可以在模板中执行以下操作:

{{ my_dict }}

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

首先,您需要创建一个 Context 对象并将其传递给渲染函数。 请参阅文档中的此示例

其次,为了使您的代码按照我认为的意图工作......您实际上需要在现有层之上添加另一层,以便您可以在模板中引用my_dict

t.render(Context({'my_dict': {'boo': {'id':'42'}, 'hi': {'id':'42'}}}))

最新更新