python - 在 Python 脚本中使用 HTML email 使用 for 循环显示 python 列表

标签 python html

我有一个用 Python 制作的列表,名为 list_servers,其中包含服务器列表。

我正在尝试在 python 脚本中发送一封电子邮件,该脚本使用 HTML 以可读的方式显示列表,但是,我不知道如何在 HTML 中使用 for 循环。

我尝试使用 Jinja2 模块,但是出现以下错误:

KeyError: '% for item in list %'

html = """\
<html>
<head></head>
<body>
<p>The file attached contains the servers.</p>
{% for item in list %}
    <li>{{ item }}</li>
{% endfor %}

</body>
</html>
""".format(list=list_servers)

无法找出错误,如果有其他方法,请告诉我!

最佳答案

您似乎混淆了两个不同的过程。 完成任务的第一种方法是先构建 html 列表,然后将其插入整个 html 部分:

list_servers = ['boo', 'foo', 'bar']
# building the auxiliary string list
items = ["\n    <li>{}</li>".format(s) for s in list_servers]
items = "".join(items)
# insert in the html 
html = """\
<html>
<head></head>
<body>
<p>The file attached contains the servers.</p>{0}
</body>
</html>
""".format(items)

上述方法使用了Python内置的.format函数。它对于示例中的简单情况有效。然而,对于更复杂的 HTML 构造,您可能需要坚持使用 jinja2 功能,如下所示:

from jinja2 import Environment, BaseLoader
# your template as a string variable
html_template = """\
<html>
<head></head>
<body>
<p>The file attached contains the servers.</p>
{% for server in servers %}
    <li>{{ server }}</li>
{% endfor %}

</body>
</html>
"""
# jinja2 rendering
template = Environment(loader=BaseLoader).from_string(html_template)
template_vars = {"servers": list_servers ,}
html_out = template.render(template_vars)
print(html_out)

关于python - 在 Python 脚本中使用 HTML email 使用 for 循环显示 python 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971956/

相关文章:

HTML5 视频在 FireFox 浏览器中显示 "No Video With Supported format and MIME type Found"

php - 在html表格中显示数组

html - 按钮未正确连接到输入

python - 如何在 Django 中为多值 cookie 指定分隔符?

python - Downloader.py 未返回正确的 JSON 对象不起作用

python - 使用 SPSS Python 脚本获取列值

java - 如何将动态参数传递给jquery函数

如果选择达到数字,JavaScript 会发出警报

python - 求解平方奇异系统?

python - 制作字典列表按值传递