Skip to content

Commit 8cdc5ab

Browse files
adding a jinja2 example to the interactive HTML export
Jinja2 is a standard, safe, and powerful way to insert content into HTML in Python. I add an example to the documentation
1 parent 1e551da commit 8cdc5ab

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

doc/python/interactive-html-export.md

+23
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,29 @@ fig.write_html("path/to/file.html")
5555

5656
By default, the resulting HTML file is a fully self-contained HTML file which can be uploaded to a web server or shared via email or other file-sharing mechanisms. The downside to this approach is that the file is very large (5Mb+) because it contains an inlined copy of the Plotly.js library required to make the figure interactive. This can be controlled via the `include_plotlyjs` argument (see below).
5757

58+
### Inserting Plotly Output into HTML using a Jinja2 Template
59+
60+
You can insert Plotly output and text related to your data into HTML templates using Jinja2. First create an HTML template file containing a variable like `{{ fig }}`. Then use the following Python to replace `{{ fig }}` in the template with HTML that will display the Plotly figure "fig":
61+
62+
```
63+
import plotly.express as px
64+
from jinja2 import Template
65+
66+
data_canada = px.data.gapminder().query("country == 'Canada'")
67+
fig = px.bar(data_canada, x='year', y='pop')
68+
69+
output_html_path=r"/path/to/output.html"
70+
input_template_path = r"/path/to/template.html"
71+
72+
plotly_jinja_data = {"fig":fig.to_html(full_html=False)}
73+
#consider also defining the include_plotlyjs parameter to point to an external Plotly.js as described above
74+
75+
with open(output_html_path, "w", encoding="utf-8") as output_file:
76+
with open(input_template_path) as template_file:
77+
j2_template = Template(template_file.read())
78+
output_file.write(j2_template.render(plotly_jinja_data))
79+
```
80+
5881

5982
### HTML export in Dash
6083

0 commit comments

Comments
 (0)