将 dash_html_components 传递到 Jinja 模板中

2024-03-13

我正在使用 Python 库 Dash,文档声称它不支持使用仪表板 html 代码编写原始 html 的功能。是否有已知的解决方法(例如传递dcc.Graph into render_template()与烧瓶?)。

我想要迁移到 Jinja 模板文件的代码片段是:

app.layout = html.Div(className='ui container', children=[
    html.H1('Locations', className=''),
    html.Div(id='text-content'),
    dcc.Graph(id='map', figure={
        'data': [{
            'lat': df['LAT'],
            'lon': df['LONG'],
            'marker': {
                'color': df['YEAR'],
                'size': 8,
                'opacity': 0.6
            },
            'customdata': df['NO'],
            'type': 'scattermapbox'
        }],
            },
            'hovermode': 'closest',
            'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0}
        }
    })
])

我以前来过这里并亲自问过这个问题,我继续在这里回答:Plotly.offline 绘图 output_type='div' 在 HTML 中不起作用 - 如何将 Plotly 嵌入到 HTML https://stackoverflow.com/questions/61682730/plotly-offline-plot-output-type-div-not-working-inside-html-how-to-embed-plo

简而言之,要获取通过 Flask 视图呈现的图表,您可以执行以下操作(取自上面的链接)

  1. 创建图表
  2. Call pyo.plot()像平常一样穿过无花果,output_type='div' and include_plotlyjs=False
  3. 将该输出传递给变量Markup()(从烧瓶导入)
  4. Markup(variable)通过了render_template就像你的表格一样
  5. 使用以下命令在 html 中呈现变量{{ jinja template }}

更实际的演示:

def my_bar_chart():
    *snip irrelevant*
    my_bar_chart = pyo.plot(fig, output_type='div', include_plotlyjs=False)
    return Markup(my_bar_chart)

现在将您的函数导入到您的 app.py / 无论您的视图在哪里,然后将其传递给渲染模板,就像任何表单一样。

这是一个例子:

def my_page():
    my_bar_chart_var = my_bar_chart()
    return render_template('my_page.html',
                            bar_chart_1=my_bar_chart_var)

然后在该页面的 html 上简单地传递bar_chart_1在 jinja 模板中,如下所示:

{{ bar_chart_1 }}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 dash_html_components 传递到 Jinja 模板中 的相关文章

随机推荐