How to render graphs in Jinja template

I’m trying to create PDFs from HTML using WeasyPrint & Jinja2. I’d like to include in these PDFs visualization using Plotly, but I do not undertand how to get a simple plot to display in the Jinja template. I have tried:

from jinja2 import Template, Environment, FileSystemLoader
from plotly.offline import plot
from plotly.graph_objs import Scatter

fig = plot([Scatter(x=[0, 1, 2, 3, 4], y=[0, 1, 4, 9, 16])], output_type='div')

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('FirstAttempt.html')
template_vars = {"title":"My Title","Plot":fig}

html_out = template.render(template_vars)

from weasyprint import HTML

HTML Template is:

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <h2>{{ title }}</h2>
        {{ Plot }}

Note that this works just fine for me if I pass a pandas df as the value of “Plot” using df.to_html(). I was hoping using the same approach would work with plotly visualization, but it apparently doesn’t. Would appreciate the help as I am the newbiest of newbs…


1 Like

Did anyone find a way to do it ?