[英]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.