【问题标题】:Having problems iterating over dict in Django template在 Django 模板中迭代 dict 时遇到问题
【发布时间】:2023-03-16 03:47:01
【问题描述】:

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

我有这样的东西:

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 %}

仍然没有任何显示。

【问题讨论】:

    标签: python django dictionary django-templates


    【解决方案1】:

    时间:

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

    用途:

    {% for k, v in test_dict.items %}
    

    【讨论】:

      【解决方案2】:

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

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

      来自docs

      要添加到模板上下文的值字典。

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

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

      所以 test_dict 并没有注入到模板的上下文中,而是 test_dict 的键和值。

      【讨论】:

      • 感谢您的及时回复。不过,它仍然没有为我显示任何数据: test_dict = {'name':'Joe'} data = {'test_dict':test_dict} return render_to_response('ga_home.html',data,context_instance=RequestContext(request))
      猜你喜欢
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 2018-09-11
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多