我有一个用 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/