Making table sortable in Dash html Table component

眉间皱痕 提交于 2021-01-05 07:18:54

问题


I have a table in my app with Dash, but I made it using the html components and not with the DataTable of Dash. The app is quite big and already configured, so I would like to avoid rewriting it. In html there is the <table class="sortable"> which makes the table sortable. However, when I construct the table with dash, where should I write this attribute? Here is my table code:

def generate_table(dataframe, max_rows=1000):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ], style={
        'margin-right': 'auto',
        'margin-left': 'auto'
        }
    )

回答1:


To add a class to a Dash component, simply pass it via the className keyword,

... style={'margin-right': 'auto', 'margin-left': 'auto'}, className="sortable")

The class itself won't make the table sortable though, you'll need to load an appropriate JavaScript library. In Dash, scrips are usually loaded on app initialization. However, for this type of library to work, it must be loaded after the table has been render, which can be achived using this library. Here is a small example,

import dash
import dash_html_components as html
import pandas as pd
import dash_defer_js_import as dji


def generate_table(dataframe, max_rows=1000):
    return html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in dataframe.columns])
        ),
        html.Tbody([
            html.Tr([
                html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
    ], style={'margin-right': 'auto', 'margin-left': 'auto'}, className="sortable")


df = pd.DataFrame({'Fruits': ["Apple", "Banana"], 'Vegetables': ["Tomato", "Cucumber"]})
app = dash.Dash()
app.layout = html.Div([generate_table(df), dji.Import(src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js")])

if __name__ == '__main__':
    app.run_server()


来源:https://stackoverflow.com/questions/63793969/making-table-sortable-in-dash-html-table-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!