Passing dash_html_components into a Jinja template Passing dash_html_components into a Jinja template flask flask

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)

  1. Create a chart
  2. Call pyo.plot() as normal passing through the fig, output_type='div' and include_plotlyjs=False
  3. Have that output to a variable passed through Markup() (import from flask)
  4. Have the Markup(variable) passed through the render_template like you would a form
  5. 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 }}