【问题标题】:Django template not displaying looped keys, valuesDjango模板不显示循环键、值
【发布时间】:2017-09-22 15:59:57
【问题描述】:

我对 Django 很陌生,我想弄清楚为什么我可以按预期在模板中调用字典中的键,但是循环遍历字典不会产生任何文本,也不会产生任何错误消息。我不想硬编码键名(即在我的模板中低于msgid,因为字典是动态的,所以我只想循环遍历它。

views.py

class Pymat_program(View):
    def get(self, request, *args, **kwargs):
        selected_xml = 'a_directory_to_my_file'
        smsreport_dict = self.parse_xml_file(selected_xml)
        html = self.populate_html_text(smsreport_dict)

        return HttpResponse(html)

    def populate_html_text(self, smsreport_dict):
        t = get_template('template2.html')
        html = t.render(smsreport_dict)

        return html

template2.html

    <p>MSGID: {{ msgid }}</p>

    <p> Begin
    {% for key, value in smsreport_dict %}
        <tr>
            <td> Key: {{ key }} </td> 
        </tr>
    {% endfor %}
    </p>End

在 template2.html 中,您可以看到 msgid 值(smsreport_dict 中的几个值之一)被调用,它显示在我的页面上。但由于某种原因,smsreport_dict 循环不会产生任何文本。我哪里错了?

【问题讨论】:

  • 在你的方法populate_html_text中尝试t.render(context={'smsreport_dict':smsreport_dict})
  • @ Jens, ozgur:解决方案是您的两个答案的结合。我需要在我的模板中添加项目,加上 context={'smsreport_dict':smsreport_dict}。谢谢!

标签: python django django-templates


【解决方案1】:

smsreport_dict 应该在您用来渲染模板的Context 内:

...
html = t.render(Context({"smsreport_dict": smsreport_dict}))
...

另外,您在遍历模板中的字典时忘记调用.items

{% for key, value in smsreport_dict.items %}
  ...

【讨论】:

    【解决方案2】:

    你需要将.items添加到smsreport_dict

    MSGID:{{ msgid }}

    <p> Begin
    {% for key, value in smsreport_dict.items %}
        <tr>
            <td> Key: {{ key }} </td> 
        </tr>
    {% endfor %}
    </p>End
    

    请参阅here 了解类似情况。

    【讨论】:

      猜你喜欢
      • 2014-03-09
      • 2017-03-27
      • 2018-03-08
      • 2018-12-27
      • 2016-09-14
      • 2011-04-27
      • 2021-05-26
      • 2020-09-29
      • 1970-01-01
      相关资源
      最近更新 更多