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

时间:2014-06-10 04:21:33

标签: python html templates html-email

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

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

我想要这样的事情:

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

3 个答案:

答案 0 :(得分:7)

我希望在Flask框架内使用Jinja做同样的事情。以下是借鉴Miguel Grinberg's Flask tutorial

的示例
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>

答案 1 :(得分:4)

我将扩展@ 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​​与模板的示例的link

答案 2 :(得分:0)

您可以使用Jinja2,这是Python的模板语言。它具有模板继承功能。从官方文档中查看此example

相关问题