繁体   English   中英

在Django模板中遍历字典

[英]iterate through a dictionary in django template

{'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 ', ', ']}

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

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

我在我的html文件中尝试过这个,其中put是我通过视图传递的变量

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

还有这个:

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

但是我没有任何输出。 屏幕上空白无显示

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>

首先,您的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/zh-CN/2.0/topics/http/shortcuts/#render

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

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

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM