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

8
我有一个Python脚本,想将其作为每日cron作业执行,向所有用户发送电子邮件。目前我在脚本中硬编码了html内容,看起来很杂乱。我已经阅读了文档,但我还没有弄清楚如何在我的脚本中渲染模板。
是否有任何方法可以使用带有占位符的单独html文件,然后使用Python填充并将其发送为电子邮件正文?
我想要这样的东西:
mydict = {}
template = '/templates/email.j2'
fillTemplate(mydict)
html = getHtml(filledTemplate)
3个回答

8

我想使用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)

它假设类似以下模板的内容:

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>

1
如果您想传递一个字符串,可以使用flask.render_template_string - Alan Hamlett

8
我将扩展@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的示例链接

1
你可以使用Jinja2,这是一个用于Python的模板语言。它具有模板继承功能。请查看官方文档中的example示例。

但是我该如何在Python程序中实现这一点,我的意思是在Python中加载模板,填充它,然后获取其HTML呢? - Mirage
固定引用,谢谢! - Mauro Baraldi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接