我的表格是根据数据库中的内容生成的,并且希望添加基于特定列对表格进行排序的功能。我尝试在线查看,但由于表格不是静态的,我不确定如何正确添加排序功能。
<table class="table" style="border: 3px solid black;">
<thead>
<tr>
<th style="border-left: 1px solid #eee;" class="align-middle">Select</th>
<th class="align-middle">Col1</th>
<th class="align-middle">Col2</th>
<th class="align-middle">Col3</th>
<th class="align-middle">Col4</th>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td><input type="checkbox" name="inputSelect" value="{{ row[0], row[3] }}"></td>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
答案 0 :(得分:0)
没关系,这对我来说非常有用:https://datatables.net/manual/installation
答案 1 :(得分:0)
创建可排序表的一种解决方案是在 flask-tables 内。链接的文章在 solution.py 中还有一个最小示例。
完整示例可在 solution.py
中找到,但最重要的部分是:
class SortableTable(Table):
id = Col('ID')
name = Col('Name')
description = Col('Description')
link = LinkCol(
'Link', 'flask_link', url_kwargs=dict(id='id'), allow_sort=False)
allow_sort = True
def sort_url(self, col_key, reverse=False):
if reverse:
direction = 'desc'
else:
direction = 'asc'
return url_for('index', sort=col_key, direction=direction)
@app.route('/')
def index():
sort = request.args.get('sort', 'id')
reverse = (request.args.get('direction', 'asc') == 'desc')
table = SortableTable(Item.get_sorted_by(sort, reverse),
sort_by=sort,
sort_reverse=reverse)
return table.__html__()
如果您想将它与像我一样的 Pandas 结合使用,这是一个可以帮助您的最小示例:
from flask_table import Table, Col
from flask import Flask, request, url_for
import pandas as pd
"""
A example for creating a Table that is sortable by its header
"""
app = Flask(__name__)
class SortableTable(Table):
id = Col('ID')
name = Col('Name')
description = Col('Description')
allow_sort = True
def sort_url(self, col_key, reverse=False):
if reverse:
direction = 'desc'
else:
direction = 'asc'
return url_for('index', sort=col_key, direction=direction)
@app.route('/')
def index():
df = pd.DataFrame([
(1, 'G', 'zzzzz'),
(2, 'U', 'aaaaa'),
(3, 'I', 'bbbbb')], columns=["id", "name", "description"])
sort = request.args.get('sort', 'id')
reverse = (request.args.get('direction', 'asc') == 'desc')
df = df.sort_values(by=[sort], ascending=reverse)
output_dict = df.to_dict(orient='records')
table = SortableTable(output_dict,
sort_by=sort,
sort_reverse=reverse)
return table.__html__()
if __name__ == '__main__':
app.run(debug=True)