gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:30:12 24 4
gpt4 key购买 nike

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

有什么方法可以让我拥有单独的带有占位符的 html 文件,我可以使用 python 填充它,然后将其作为电子邮件正文发送?

我想要这样的东西:

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

最佳答案

我想在 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)

它假定类似于以下模板:

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>

关于python - 如何在 Python 程序中使用 Jinja2 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24132811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com