提问人:thatmare 提问时间:9/4/2023 更新时间:9/4/2023 访问量:104
如何使用Jinja2渲染HTML电子邮件模板?
How to render an HTML email template with Jinja2?
问:
我想使用 Jinja2 和 Python 在 HTML 电子邮件模板中动态呈现数据。我是 Python 和 Jinja2 的新手。这是我到目前为止所做的:
- 我的样板
dynamic
/dynamic.html
/script.py
- 我有我的HTML模板。只是向您展示我从 Jinja2 添加循环的摘录:
for
<table bgcolor="#FEF8D5" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td align="center" bgcolor="#FEF8D5" cellspacing="0">
<h2 style="font-family: Helvetica, sans-serif; font-size: 31px; color: #FF341A;">Honorable Mentions</h2>
</td>
</tr>
<tr align="center" valign="center">
{% for movie in data["movies"] %}
<p>{{ movie["title"] }}</p>
{% endfor %}
</tr>
</table>
- 我有一个Python脚本:
from jinja2 import Template, Environment, FileSystemLoader
env = Environment(
loader=FileSystemLoader('.')
)
template = env.get_template('dynamic.html')
def get_data():
data = []
data.append(
{
"movies": [
{
"title": 'Terminator',
"description": 'One soldier is sent back to protect her from the killing machine. He must find Sarah before the Terminator can carry out its mission.'
},
{
"title": 'Seven Years in Tibet',
"description": 'Seven Years in Tibet is a 1997 American biographical war drama film based on the 1952 book of the same name written by Austrian mountaineer Heinrich Harrer on his experiences in Tibet.'
},
{
"title": 'The Lion King',
"description": 'A young lion prince is born in Africa, thus making his uncle Scar the second in line to the throne. Scar plots with the hyenas to kill King Mufasa and Prince Simba, thus making himself King. The King is killed and Simba is led to believe by Scar that it was his fault, and so flees the kingdom in shame.'
}
]
})
return data
data = get_data()
output = template.render(data=data[0])
print(output)
当我在控制台中运行时,它为我提供了正确呈现的整个 HTML:这意味着带有电影标题的元素。这让我认为我没有任何语法错误。但是,当我在浏览器中打开 HTML 文件时,标题不会呈现,它只显示 Jinja 代码。python script.py
<p>
据我阅读和理解,没有必要使用 Flask 来渲染 Jinja,而且由于我不是在创建一个 Web 应用程序,而是一封电子邮件,我不确定这样做是否必要或合适。
感谢您的帮助。
答:
1赞
AKX
9/4/2023
#1
如果您要打开 ,那么,好吧,这就是您的模板,它显示 Jinja 模板是一件好事。dynamic.html
在示例中,您没有将输出写入文件(只是将其打印到终端),因此可以添加
with open("output.html") as f:
f.write(output)
最后,然后在浏览器中打开。output.html
评论