Flask中Jinja2模板如何将列表元素对应表格列迭代展示?
解决方法
第一步:修改Python函数,结构化设备数据
你当前的函数把所有设备的属性平铺到了一个列表里,导致模板无法区分每个设备的不同字段。需要把每个设备的信息封装成字典,让列表里的每个元素对应一台设备的完整数据:
def canaries_up_time(results): results = results.json() newlist = [] for item in results['devices']: # 将单台设备的所有属性封装为字典 device_data = { "hostname": item.get("name"), "ip_address": item.get("ip_address"), "uptime": item.get("uptime"), "location": item.get("location") } newlist.append(device_data) return newlist
第二步:修改模板,按列渲染表格
去掉模板里的<ul>和<li>标签,改为循环每个设备数据,生成表格行和对应列:
{% extends "base.html" %} {% block app_content %} <table class="table table-hover table-striped"> <thead> <tr> <th style="text-align: center">Hostname</th> <th style="text-align: center">IP_address</th> <th style="text-align: center">uptime</th> <th style="text-align: center">location</th> </tr> </thead> <tbody> {% for device in newlist %} <tr> <td style="text-align: center">{{ device.hostname }}</td> <td style="text-align: center">{{ device.ip_address }}</td> <td style="text-align: center">{{ device.uptime }}</td> <td style="text-align: center">{{ device.location }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %}
原理说明
修改后,newlist里的每个元素都是包含单台设备所有属性的字典,模板循环时可以精准提取每个字段的值,对应填入表格的列中,实现你想要的分栏展示效果。
内容的提问来源于stack exchange,提问作者user18704773
相关产品推荐
相关产品推荐

