简体   繁体   English

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

[英]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. 我有一个python脚本,我想作为每日cron作业执行,以向所有用户发送电子邮件。 Currently I have hard-coded the html inside the script and it looks dirty. 目前我已经在脚本中对html进行了硬编码,看起来很脏。 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? 有没有办法,我可以使用占位符单独的html文件,我可以使用python填充,然后作为电子邮件的正文发送?

I want something like this: 我想要这样的东西:

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

I was looking to do the same thing using Jinja within the Flask framework. 我希望在Flask框架内使用Jinja做同样的事情。 Here's an example borrowed from Miguel Grinberg's Flask tutorial : 这是一个借鉴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)

It assumes something like the following templates: 它假定类似于以下模板:

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

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

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

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

I am going to expand on @Mauro's answer. 我将扩展@ Mauro的答案。 You would move all of the email HTML and/or text into a template file(s). 您可以将所有电子邮件HTML和/或文本移动到模板文件中。 Then use the Jinja API to read the template in from the file; 然后使用Jinja API从文件中读取模板; finally, you would render the template by providing the variables that are in the template. 最后,您将通过提供模板中的变量来呈现模板。

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

This is a link to an example of using the API with the template. 这是指向将API与模板一起使用的示例的链接

You can use Jinja2 , a template language for Python. 您可以使用Jinja2 ,Python的模板语言。 It has template inheritance feature. 它具有模板继承功能。 Look at this example from official docs. 从官方文档中查看此示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM