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

I have one python script that I want to execute as a daily cron job to send email to all users. I am currently hardcoded the html inside the script and it looks dirty. I read the documents , but I did not understand how I can display the template in my script.

Is there a way that I can have a separate html file with placeholders that I can use to populate python and then send it as an email body?

I need something like this:

mydict = {}
template = '/templates/email.j2'
fillTemplate(mydict)
html = getHtml(filledTemplate)
+4
source share
3 answers

@Mauro. HTML / . Jinja API ; , , , .

# 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')

API .

+3

, Jinja . , Miguel Grinberg Flask:

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

subject = 'Test Email'
sender = 'alice@example.com'
recipients = ['bob@example.com']

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)

- :

//test.txt

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

//test.html

<p>Hi {{ name }},</p>
<p>This is just a test.</p>
+7

Jinja2, Python. . .

0

Source: https://habr.com/ru/post/1543934/


All Articles