如何在Python程序中使用Jinja2模板?

Ran*_*ngh 5 html python templates html-email

我有一个python脚本,我想作为每日cron作业执行,以向所有用户发送电子邮件.目前我已经在脚本中对html进行了硬编码,看起来很脏.我已经阅读了文档,但我还没弄明白如何在脚本中呈现模板.

有没有办法,我可以使用占位符单独的html文件,我可以使用python填充,然后作为电子邮件的正文发送?

我想要这样的东西:

mydict = {}
template = '/templates/email.j2'
fillTemplate(mydict)
html = getHtml(filledTemplate)
Run Code Online (Sandbox Code Playgroud)

kle*_*ell 7

我希望在Flask框架内使用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)
Run Code Online (Sandbox Code Playgroud)

它假定类似于以下模板:

模板/电子邮件/的test.txt

Hi {{ name }},
This is just a test.
Run Code Online (Sandbox Code Playgroud)

模板/电子邮件/ test.html中

<p>Hi {{ name }},</p>
<p>This is just a test.</p>
Run Code Online (Sandbox Code Playgroud)


小智 5

我将扩展@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')
Run Code Online (Sandbox Code Playgroud)

这是指向将API与模板一起使用的示例的链接