user2134226 user2134226 - 9 months ago 34
HTML Question

How can I use a Jinja2 template inside a Python program?

I have one python script which I want to execute as a daily cron job to send emails to all users. Currently I have hard-coded the html inside the script and it looks dirty. I have read the docs, but I haven't figured out how can I render the template within my script.

Is there any way that I can have the separate html file with placeholders which I can use python to populate and then send as the email's body?

I want something like this:

mydict = {}
template = '/templates/email.j2'
html = getHtml(filledTemplate)


I am going to expand on Mauro's answer. You would move all of the email html and/or text into a template file(s). After you would use the jinga apis to read the template in from the file, you would then render the template by providing the variables that are in the template.

# copied directly from the docs
from jinja2 import Environment, PackageLoader

env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

This is a link to an example f using the API with the template