user2134226 user2134226 - 2 years ago 322
HTML Question

How can i use Jinja2 template inside python program

I have one

python script
which i want to execute as
cron job daily
to send
to all users

Currently i have hard coded the html inside the
t and it looks dirty.

Is there any way that i can have the separate html file with place holders which i can use in
to populate it and then send that as
email body

i don't want to attach as
but as email body

I have read this

But i haven't found how can i get the rendered template inside python

something like

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download