如何给Pandas生成的Bootstrap HTML表格最后一列加点击显示按钮
动态HTML表格大字段列折叠显示方案
问题背景
我正在开发一个动态HTML表格,数据由Python的pandas dataframe提供,表格每一行最后一列是大段论文摘要文本,导致行高过大、表格可读性和导航性差。当前技术栈使用Bootstrap CSS和JavaScript,希望将最后一列内容隐藏,通过切换按钮触发显示(popover气泡弹窗或弹窗跳转均可)。想确认两个问题:
- 是否可以仅对最后一列/单元格编写条件判断逻辑实现需求?
- 有没有其他实现方案?
原相关代码
后端Flask代码(main.py)
from flask import Flask, render_template from researchdashboard import combined_dictionaries app = Flask(__name__) headings = ("""list of headings""") for x in combined_dictionaries: data = combined_dictionaries.iloc @app.route('/') def index(): return render_template('index.html', headings=headings, data=data) if name == "__main__"_ app.run(debug=True)
注:原代码存在两处笔误,修正后可正常运行:
name改为__name__,末尾的下划线改为英文冒号。
前端初始表格模板代码
<table class="""some specifics for the table design"""> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} </tr> <tbody> {% for row in data %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table>
实现方案说明
方案1:仅针对最后一列加条件判断(无数据拆分)
可以仅针对最后一列编写判断逻辑实现需求,不需要改动后端数据结构,只需要修改前端模板即可:
- 利用Jinja2模板的
loop.last属性判断当前循环是否为最后一个元素 - 最后一列不直接渲染文本,改为渲染Bootstrap popover按钮,把摘要内容存在按钮的
data-content属性中 - 其余列正常渲染内容
示例代码如下:
<table class="""some specifics for the table design"""> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} </tr> <tbody> {% for row in data %} <tr> {% for cell in row %} {% if loop.last %} <td> <button type="button" class="btn btn-secondary" data-toggle="popover" data-placement="left" data-content="{{ cell }}"> 查看摘要 </button> </td> {% else %} <td>{{ cell }}</td> {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table>
需要额外在页面JS中初始化Bootstrap popover:
$(function () { $('[data-toggle="popover"]').popover() })
方案2:后端拆分数据(提问者最终采用方案)
提问者最终选择了后端提前拆分数据的实现逻辑,代码如下:
<table> <tr> {% for header in headings %} <th>{{ header }}</th> {% endfor %} </tr> {% for row in range(num_rows) %} <tr> {% for cell in data[row] %} <td>{{ cell }}</td> {% endfor %} <td><button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="left" data-content="{{ abstract_data[row] }}">Abstract</button></td> </tr> {% endfor %} </table>
实现逻辑说明
data变量存储剔除了待隐藏列的全部dataframe数据abstract_data变量单独存储待隐藏的摘要列,二者单独调用num_rows通过len()函数获取,入参为指定表格行数的度量值
内容的提问来源于stack exchange,提问作者staminem
相关产品推荐
相关产品推荐

