如何在Django的HTML模板中遍历嵌套Python字典生成表格
Django模板遍历嵌套字典生成表格实现方案
1. 视图层传递数据
先将构造好的字典和提前提取的表头传入模板上下文,视图示例代码如下:
# views.py from django.shortcuts import render def your_view(request): data = {"X":{"0":1234, "1":5678, "2":1234}, "Y": {"0":4567, "1":1234,"2":4456}} # 提前提取内层字典的键作为表格列头,避免模板重复处理 col_headers = list(data.values())[0].keys() return render(request, 'your_template.html', {'data': data, 'col_headers': col_headers})
2. 模板层实现方案
方案A:行首为一级键(X/Y),列头为二级键(0/1/2)
该方案无需自定义过滤器,实现最简便,最终表格结构为:
| 分类 | 0 | 1 | 2 |
|---|---|---|---|
| X | 1234 | 5678 | 1234 |
| Y | 4567 | 1234 | 4456 |
模板代码如下:
<table border="1"> <!-- 表头 --> <tr> <th>分类</th> {% for header in col_headers %} <th>{{ header }}</th> {% endfor %} </tr> <!-- 遍历一级字典生成行 --> {% for row_key, row_values in data.items %} <tr> <td>{{ row_key }}</td> <!-- 遍历二级字典的值填充单元格 --> {% for val in row_values.values %} <td>{{ val }}</td> {% endfor %} </tr> {% endfor %} </table>
方案B:行首为二级键(0/1/2),列头为一级键(X/Y)
该方案适用于需要把内层键作为行的场景,最终表格结构为:
| 序号 | X | Y |
|---|---|---|
| 0 | 1234 | 4567 |
| 1 | 5678 | 1234 |
| 2 | 1234 | 4456 |
因为Django模板默认不支持用变量作为键取字典值,需要先自定义模板过滤器:
- 在你的app目录下新建
templatetags文件夹,新增custom_filters.py文件,代码如下:
from django import template register = template.Library() @register.filter def get_item(dictionary, key): return dictionary.get(key)
- 在模板顶部引入自定义过滤器:
{% load custom_filters %}
模板代码如下:
<table border="1"> <!-- 表头 --> <tr> <th>序号</th> {% for col_key in data.keys %} <th>{{ col_key }}</th> {% endfor %} </tr> <!-- 遍历内层键生成行 --> {% for header in col_headers %} <tr> <td>{{ header }}</td> <!-- 用自定义过滤器取对应键的值 --> {% for row_values in data.values %} <td>{{ row_values|get_item:header }}</td> {% endfor %} </tr> {% endfor %} </table>
内容的提问来源于stack exchange,提问作者F_ Duenne
相关产品推荐
相关产品推荐

