Jinja2/Python insert a image(s) into html

user3582887 picture user3582887 · Mar 7, 2016 · Viewed 7.7k times · Source

I am just looking into using Jinja2 with a python application I have already written. I may be going about this in the wrong way, but here is what I would like to do.

from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("really.html")

template_vars = {"title":"TITLE","graph":'total.png'}

html_out = template.render(template_vars)

HTML(string=html_out).write_pdf("report.pdf")

This nearly produces what I want, I get a pdf called report.pdf, but instead of the attached file, it is a string of total.png. This is my first run at using Jinja, so hopefully attaching an image like this is possible. Thanks.

This is the template, not much built, just trying to do this piece at first.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
 {{ graph }}
</body>
</html>

Answer

user3582887 picture user3582887 · Mar 8, 2016

I have an answer to my own question, I was simply able to add the image url into the template, without trying to pass it in as a variable.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
 <img src="graph.png">
 </body>
 </html>

Guess I was over complicating it a bit...