迭代django模板中的字典

时间:2017-12-10 19:54:22

标签: python html django-templates

{'provide a full refund of any money paid ': ['the ', 'dith ', 'with ', 'ande ', 'cor '], 'copyright laws of the place where you ar': ['e ', 'init ', ' or ', 'ate ', 's '], 'person or entity that provided you with ': ['the ', 'of ', 'ande ', ' or ', 'project '], 'michael s. hart is the originator of the': [' the ', '\n ', 's ', 'r ', ', ']}

如何将通过我的视图传递的django变量解析为html文件。 我想让这些数据以表格的形式显示在html文件中,其中显示每个键值

return render(request, 'notebook/instant_search.html', output)

我在我的html文件中尝试了这个,其中输出是我通过我的视图的变量

{% for key, value in output %}
   {{ key }} <br>
    {% for key2 in value %}
       {{ key2 }} <br>
    {% endfor %}
{% endfor %} 

也是这样:

{% for k in context %}
    {{  k }}
{% endfor %}

但我没有得到任何输出。它的空白在屏幕上无显示

3 个答案:

答案 0 :(得分:2)

return render(request, 'notebook/instant_search.html', {"output":output})

在视图文件中更改此语句,然后通过

获得输出
<table>
{% for key, value in output.items %}
<tr>
<td>{{key}}</td>
<td>{{value}}<td> <!-- you can also run for on values list -->
</tr>
{% endfor %}
</table>

答案 1 :(得分:1)

首先,您的render函数不接受正确的参数,这就是您的html模板上没有出现任何内容的原因。你输入了这个:

return render(request, 'notebook/instant_search.html', output)

正确的一个:

return render(request, 'notebook/instant_search.html', 'output':output)

以上将解决模板不显示渲染功能数据的问题。

接下来是将遍历字典的代码:

以下内容将显示列表中的每个项目

{% for k, v in output.items %}
    {% for i in v %}
        {{ i }}
    {% endfor %}
{% endfor %}

而下面的代码将显示每个列表

{% for k, v in output.items %}
    {{ v }}
{% endfor %}

参考文献: https://docs.djangoproject.com/en/2.0/intro/tutorial03/

https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render

答案 2 :(得分:0)

您可以直接在模板中迭代字典:

<table>
{% for key, value in my_dict.items %}
    <tr>
        <td>{{key}}</td>
        <td>{{value}}<td> <!-- you can also run for on values list -->
    </tr>
{% endfor %}
</table>

希望有所帮助

相关问题