官方都没找到如何给默认的表格排序。。。结合jquery的例子改了下,默认的put_table 没有<thead>,所以需要单独分离出来head 和 rows,然后在拼接回去。
# -*- encoding: utf-8 -*-"
from pywebio.input import *
from pywebio.output import *
from pywebio import config
from flask import Flask
app = Flask(__name__)
app.config.from_object('flask_config')
js_code = '''
$(document).on('click','th',function(){
var table = $(this).parents('table').eq(0);
var head = table.find('tr:eq(0)').toArray()
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc){rows = rows.reverse();}
table.children('tbody').empty().html(head).append(rows);
});
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ?
valA - valB : valA.localeCompare(valB);
};
}
function getCellValue(row, index){
return $(row).children('td').eq(index).text();
}
'''
@config(js_code=js_code)
def test():
put_table([
['Commodity', 'Price', 'Count'],
['Apple', '5.5', 4],
['Banana', '7', 2],
['orange', '3', 5]
])
if __name__ == '__main__':
# `task_func` is PyWebIO task function
app.add_url_rule('/', 'test', webio_view_local(test), methods=['GET', 'POST'])
app.run(host='0.0.0.0', port=5000)
参考文档:
https://www.hujiangtao.cn/2017/03/jquery-table-order/#%E7%9B%AE%E5%BD%95
https://pywebio.readthedocs.io/en/latest/guide.html