如何在HTML表格中展示嵌套Python字典,实现键为列值为行的效果
解决方案
你当前代码的问题是直接将完整内层字典输出到单个单元格,没有拆分字段渲染,按以下逻辑调整即可实现「内层字典键为表头、对应值为行数据」的效果:
调整后的模板代码
如果你的内层字典结构固定(固定为name/age/height三个字段),直接使用写死字段的方案最稳定:
<table class="u-full-width" id="table2"> <thead> <tr> <th style="text-align:center">序号</th> <th style="text-align:center">name</th> <th style="text-align:center">age</th> <th style="text-align:center">height</th> </tr> </thead> <tbody> {% for key, value in dict_items.items %} <tr> <th scope="row" style="text-align:center">{{ key }}</th> <td style="text-align:center">{{ value.name }}</td> <td style="text-align:center">{{ value.age }}</td> <td style="text-align:center">{{ value.height }}</td> </tr> {% endfor %} </tbody> </table>
动态字段适配方案
如果内层字典的字段是动态变化的,建议先在后端视图代码中提前提取表头作为独立上下文变量传入模板,避免前端取值报错:
- 后端视图新增代码示例(Python):
# 提取表头 if dict_items: headers = list(next(iter(dict_items.values())).keys()) else: headers = [] # 把headers和dict_items一起传到模板上下文 return render(request, '你的模板路径.html', {'dict_items': dict_items, 'headers': headers})
- 对应动态模板代码:
<table class="u-full-width" id="table2"> <thead> <tr> <th style="text-align:center">序号</th> {% for col in headers %} <th style="text-align:center">{{ col }}</th> {% endfor %} </tr> </thead> <tbody> {% for key, value in dict_items.items %} <tr> <th scope="row" style="text-align:center">{{ key }}</th> {% for field_val in value.values %} <td style="text-align:center">{{ field_val }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
内容的提问来源于stack exchange,提问作者kitchen800
相关产品推荐
相关产品推荐

