我试图在数据表中添加超链接,但他们只是不会渲染,有人可以帮助我吗?

问题描述 投票:0回答:1

在这里,我尝试使用generate_links将超链接包装到df中存在的所有sys_id,我试图将它们作为数据表显示在ui中,但它只是不会渲染



def generate_link(sys_id):
    base_url = 'some_url/{sys_id}'
    url = base_url + sys_id
    return f'<a href="{url}"> {sys_id}</a>'

@app.callback(
    Output('datatable', 'children'),
    [Input('refresh-button', 'n_clicks'),
     Input('incident-date', 'value')]
)

def data_table(n_clicks, incident_date):
    if n_clicks is not None and n_clicks > 0:
        
        # df=get_servicenow_info()
        df = pd.read_csv('/Users/unraveldata/Documents/servicenow/servicenow/assets/state2.csv')
    
        if incident_date == 'option1':  # Today
            filtered_df = df[df['created_at'].str.startswith(timestamp)]
        elif incident_date == 'option2':  # Last 7 days
            filtered_df = df[df['created_at'] >= seven_days_ago_timestamp]
        elif incident_date == 'option3':  # Last 30 days
            filtered_df = df[df['created_at'] >= thirty_days_ago_timestamp]
            
        filtered_df['sys_id'] = filtered_df['sys_id'].apply(generate_link)
        
        layout = [
                dbc.Col(
                children=[
                    dash_table.DataTable(
                        data=filtered_df.to_dict('records'),
                        columns=[{"name": i, "id": i} for i in df.columns],       
                        page_action='native',    
                        page_size=10,
                        style_table={'overflowX': 'auto'},
                        unsafe_allow_html=True,
                    )
                ]
            )
        ]
        return layout

这是数据表中的样子 0852031c47e002107622b979316d4355

python html datatable hyperlink plotly-dash
1个回答
0
投票

如果您不介意使用更简单的东西来说明如何做到这一点。我在代码中添加了注释。

app = Dash(
    name=__name__
)

# Sample data
data = [
    {'Name': 'John', 'Age': 30, 'Website': 'http://example.com/john'},
    {'Name': 'Alice', 'Age': 25, 'Website': 'http://example.com/alice'},
    {'Name': 'Bob', 'Age': 35, 'Website': 'http://example.com/bob'}
]

# Add a new field to the data
modified_data = [
    {
        **row,  # spread in existing columns
        'link': f"[Visit {row['Name']}]({row['Website']})"  # add new link column
    }
    for row in data
]

# Define columns
# Note: We're using a new column called link instead of col 'Website' in dataset
columns = [
    {'name': 'Name', 'id': 'Name'},
    {'name': 'Age', 'id': 'Age'},
    {'name': 'Website', 'id': 'link', 'presentation': 'markdown'}
]


app.layout = html.Div(
    dash_table.DataTable(
        data=modified_data,
        columns=columns
    )
)

上面的代码将返回类似这样的内容

© www.soinside.com 2019 - 2024. All rights reserved.