You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何将含嵌套列表的字典正确渲染为HTML表格

OSPF邻居信息字典渲染HTML表格重复问题解决

问题背景

  • 现有值为嵌套列表结构的字典,需要以HTML表格形式结构化展示OSPF邻居数据
  • 表格要求:每一行对应一条邻居条目,列包含Hostname、Address、Interface、State、ID,填入对应匹配的字段值
  • 初始实现使用多层嵌套循环,出现数据重复、字段错位问题

源数据

传入模板的字典变量为ospfdictkey,结构如下:

{
  'hostname': [['R1-ISP'], ['R2-ISP']],
  'ospfneighboraddress': [['192.168.5.2', '192.168.5.13', '192.168.5.25'], ['192.168.5.1', '192.168.5.6', '192.168.5.32']],
  'ospfneighborinterface': [['ae1.0', 'ae4.0', 'ae7.0'], ['ae1.0', 'ae2.0', 'ae9.0']],
  'ospfneighborstate': [['Full', 'Full', 'Full'], ['Full', 'Full', 'Full']],
  'ospfneighborID': [['172.0.0.2', '172.0.0.4', '172.0.0.5'], ['172.0.0.1', '172.0.0.3', '172.0.0.6']]
}

错误原有代码

原有模板代码使用三层无关联嵌套循环,遍历逻辑为笛卡尔积交叉匹配,直接导致数据重复:

{% for ip in listip %}
  {% for ospfadd in ospfdictkey.ospfneighboraddress %}
  {% for a in ospfadd %}
  <tr>
    <td>{{ a }}</td>
  </tr>
  {% endfor %}
  {% endfor %}
{% endfor %}

错误渲染效果:
错误渲染的HTML表格

问题根源

源数据的索引是严格对齐的:

  1. 字典每个键对应的第i个嵌套列表,归属第i个hostname设备
  2. 每个嵌套列表内的第j个元素,对应该设备下第j个邻居的对应属性
    原有循环没有按索引绑定同设备、同邻居的关联属性,只是做全量交叉遍历,必然出现重复和错位。

正确实现代码

按索引分层遍历,先定位设备,再定位该设备下的每个邻居,按索引取对应属性填充列即可:

<table border="1">
  <thead>
    <tr>
      <th>Hostname</th>
      <th>Address</th>
      <th>Interface</th>
      <th>State</th>
      <th>ID</th>
    </tr>
  </thead>
  <tbody>
  {% for device_idx in range(ospfdictkey.hostname|length) %}
    {# 取当前索引对应的设备名和该设备下所有邻居的属性列表 #}
    {% set current_host = ospfdictkey.hostname[device_idx][0] %}
    {% set addrs = ospfdictkey.ospfneighboraddress[device_idx] %}
    {% set intfs = ospfdictkey.ospfneighborinterface[device_idx] %}
    {% set states = ospfdictkey.ospfneighborstate[device_idx] %}
    {% set ids = ospfdictkey.ospfneighborID[device_idx] %}
    {# 遍历当前设备下的每一个邻居,按索引匹配各字段 #}
    {% for nbr_idx in range(addrs|length) %}
    <tr>
      <td>{{ current_host }}</td>
      <td>{{ addrs[nbr_idx] }}</td>
      <td>{{ intfs[nbr_idx] }}</td>
      <td>{{ states[nbr_idx] }}</td>
      <td>{{ ids[nbr_idx] }}</td>
    </tr>
    {% endfor %}
  {% endfor %}
  </tbody>
</table>

代码中无意义的listip循环可以直接删除,不需要额外的外层遍历。

内容的提问来源于stack exchange,提问作者justhelpme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 05:12:35