Passing dash_html_components into a Jinja template
I have been here before and asked this question myself which I went on to answer here: Plotly.offline plot output_type='div' not working inside HTML - How to embed Plotly to HTML
In a nutshell, to get a plotly chart rendered via a Flask view you can do the following (taken from the above link)
- Create a chart
- Call
pyo.plot()
as normal passing through the fig,output_type='div'
andinclude_plotlyjs=False
- Have that output to a variable passed through
Markup()
(import from flask) - Have the
Markup(variable)
passed through therender_template
like you would a form - Have the variable rendered in the html using
{{ jinja template }}
A bit more of a practical demonstration:
def my_bar_chart(): *snip irrelevant* my_bar_chart = pyo.plot(fig, output_type='div', include_plotlyjs=False) return Markup(my_bar_chart)
Now import your function to your app.py / wherever your views are and pass it through render template as you would any form, for example.
Here is an example:
def my_page(): my_bar_chart_var = my_bar_chart() return render_template('my_page.html', bar_chart_1=my_bar_chart_var)
Then on the html for that page simply pass through bar_chart_1
in a jinja template like so:
{{ bar_chart_1 }}