Bootstrap表格实现数据行大于1时折叠展开的技术问题
解决方案:调整数据结构 + Bootstrap 手风琴折叠表格
你的核心问题确实出在数据结构的层级设计上——原结构将同类别下的所有属性值放在列表中,无法直接对应每行的完整数据,也难以构建折叠所需的父子层级。下面是具体的修复步骤:
1. 预处理数据结构
首先在Flask中把原始数据转换为类别-子项的层级结构,这样能轻松区分父类别(折叠触发)和子条目(折叠内容):
@app.route("/") def index(): # 原始数据(保留你的输入格式) original_fruit = [ {"name": ["apple", "red apple", "green apple", "yellow apple"], "taste": ["crunchy", "juicy", "sweet", "sour"], "price": [5, 4, 4, 2]}, {"name": ["watermelon"], "taste": ["sweet"], "price": [4.5]} ] # 转换为层级结构 processed_data = [] for idx, group in enumerate(original_fruit): # 自动生成类别名称(可根据业务需求修改) category = "苹果系列" if idx == 0 else "单一产品" # 拆分每个子项为独立字典 items = [] for name, taste, price in zip(group["name"], group["taste"], group["price"]): items.append({"name": name, "taste": taste, "price": price}) processed_data.append({"category": category, "items": items}) return render_template("index.html", data=processed_data)
2. HTML模板实现折叠效果
使用Bootstrap的手风琴组件,结合表格实现折叠/展开功能,同时区分多产品(折叠)和单一产品(直接显示)的场景:
<!-- 先引入Bootstrap依赖 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <div class="container mt-4"> <table class="table table-bordered"> <thead> <tr> <th>类别</th> <th>名称</th> <th>口味</th> <th>价格</th> </tr> </thead> <tbody> {% for group in data %} {% if group.items|length > 1 %} <!-- 多产品:显示折叠行 --> <tr> <td colspan="4"> <button class="btn btn-link w-100 text-start" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ loop.index }}" aria-expanded="false"> {{ group.category }} (共{{ group.items|length }}项) </button> </td> </tr> <tr> <td colspan="4" class="p-0"> <div class="collapse" id="collapse-{{ loop.index }}"> <table class="table table-borderless mb-0"> <tbody> {% for item in group.items %} <tr> <td></td> <td>{{ item.name }}</td> <td>{{ item.taste }}</td> <td>{{ item.price }}</td> </tr> {% endfor %} </tbody> </table> </div> </td> </tr> {% else %} <!-- 单一产品:直接显示一行 --> <tr> <td>{{ group.category }}</td> <td>{{ group.items[0].name }}</td> <td>{{ group.items[0].taste }}</td> <td>{{ group.items[0].price }}</td> </tr> {% endif %} {% endfor %} </tbody> </table> </div>
关键说明
- 数据结构转换后,每个类别下的子项都是独立的字典,确保每行数据完整对应。
- 利用Bootstrap的
collapse组件实现折叠逻辑,父行按钮控制子行的显示/隐藏。 - 通过
length判断自动切换显示模式:多产品显示折叠,单一产品直接展示。
内容的提问来源于stack exchange,提问作者VIncent
相关产品推荐
相关产品推荐

