Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
fillTemplate(mydict)
html = getHtml(filledTemplate)
like image 957
Mirage Avatar asked Jun 10 '14 04:06

Mirage


People also ask

How do you call a Python function in Jinja?

Use jinja2. Template. globals to call a function in a jinja2 template. Create a format string that applies a function by calling "{{ func(input) }}" apply the function func to input .


1 Answers

I was looking to do the same thing using Jinja within the Flask framework. Here's an example borrowed from Miguel Grinberg's Flask tutorial:

from flask import render_template
from flask.ext.mail import Message
from app import mail

subject = 'Test Email'
sender = '[email protected]'
recipients = ['[email protected]']

msg = Message(subject, sender=sender, recipients=recipients)
msg.body = render_template('emails/test.txt', name='Bob') 
msg.html = render_template('emails/test.html', name='Bob') 
mail.send(msg)

It assumes something like the following templates:

templates/emails/test.txt

Hi {{ name }},
This is just a test.

templates/emails/test.html

<p>Hi {{ name }},</p>
<p>This is just a test.</p>
like image 194
klenwell Avatar answered Oct 08 '22 22:10

klenwell