Skip to content

Commit e285e63

Browse files
authored
Merge pull request #4472 from rl-utility-man/patch-2
adding a jinja2 example to the interactive HTML export
2 parents 1e551da + bb55df0 commit e285e63

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Diff for: doc/python/interactive-html-export.md

+36
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,42 @@ 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. Use `.to_html` to send the HTML to a Python string variable rather than using `write_html` to send the HTML to a disk file. Use the `full_html=False` option to output just the code necessary to add a figure to a template. We don't want to output a full HTML page, as the template will define the rest of the page's structure — for example, the page's `HTML` and `BODY` tags. First create an HTML template file containing a Jinja `{{ variable }}`. In this example, we customize the HTML in the template file by replacing the Jinja variable `{{ fig }}` with our graphic `fig`.
61+
62+
```
63+
<!DOCTYPE html>
64+
<html>
65+
<body>
66+
<h1>Here's a Plotly graph!</h1>
67+
{{ fig }}
68+
<p>And here's some text after the graph.</p>
69+
</body>
70+
</html>
71+
```
72+
73+
Then use the following Python to replace `{{ fig }}` in the template with HTML that will display the Plotly figure "fig":
74+
75+
```
76+
import plotly.express as px
77+
from jinja2 import Template
78+
79+
data_canada = px.data.gapminder().query("country == 'Canada'")
80+
fig = px.bar(data_canada, x='year', y='pop')
81+
82+
output_html_path=r"/path/to/output.html"
83+
input_template_path = r"/path/to/template.html"
84+
85+
plotly_jinja_data = {"fig":fig.to_html(full_html=False)}
86+
#consider also defining the include_plotlyjs parameter to point to an external Plotly.js as described above
87+
88+
with open(output_html_path, "w", encoding="utf-8") as output_file:
89+
with open(input_template_path) as template_file:
90+
j2_template = Template(template_file.read())
91+
output_file.write(j2_template.render(plotly_jinja_data))
92+
```
93+
5894

5995
### HTML export in Dash
6096

0 commit comments

Comments
 (0)