python - 在 Django 模板中迭代 dict 时遇到问题

标签 python django dictionary django-templates

似乎有一百万个与此相关的问题(和答案),但没有一个对我有用。

我有这样的东西:

test_dict = {'name':'Joe'}
return render_to_response('home.html',test_dict,context_instance=RequestContext(request))

在模板中,我尝试这样做:

{% for k,v in test_dict.items %}
  Hello {{ v }} <br />
{% endfor %}

但运气不佳。另一方面,这有效:

Hello {{ name }}

(无 for 循环)。我一定错过了一些非常明显的东西?

编辑
为了回应第一个答案,我也尝试过:

test_dict = {'name':'Joe'}
data = {'test_dict':test_dict}

return render_to_response('home.html',data,context_instance=RequestContext(request))

在模板中:

{% block content %}
  {% for k, v in data.items %}
    Hello {{ v }} <br />
  {% endfor %}
{% endblock %}

仍然没有任何显示。

最佳答案

要做你想做的事,你会想要类似的东西

data = {'test_dict':test_dict}
return render_to_response('home.html',data,context_instance=RequestContext(request))

来自docs

A dictionary of values to add to the template context.

因此,在您的示例中,test_dict 被注入(inject)到模板上下文中。想象一下它是这样工作的:

template = Template()
for k, v in dictionary.items():
    template[k] = v

因此 test_dict 不会注入(inject)到模板的上下文中,但 test_dict 的键和值会注入(inject)。

关于python - 在 Django 模板中迭代 dict 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183903/

相关文章:

python - 在 Python 中即时在磁盘上构造稀疏矩阵

python - 使用django上传文件

python - xlsxwriter 消耗太多内存并且进程被终止

dictionary - 在 Ocaml 中映射为全局变量

javascript - 创建包含具有所有值的相同字母的所有键的映射

dictionary - 如何在Vim中映射(别名)命令

python - 在 QTreeView 中用不同的图标显示文件夹/文件

python - 在浏览器中渲染抓取数据而不存储在数据库中

django - Django-用户模型外键

python - 如何在我的模型覆盖率测试中获得 100%?