user2134226 user2134226 - 7 months ago 123
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
emails
to all users

Currently i have hard coded the html inside the
scrip
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
python
to populate it and then send that as
email body
.

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

I have read this

http://jinja.pocoo.org/docs/

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

something like

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

Answer

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