我有一个用Python制成的列表,叫做list_servers,其中包含服务器列表。
我正在尝试在python脚本中发送电子邮件,该脚本使用HTML以可读的方式显示列表,但是,我无法弄清楚如何在HTML中使用for循环。
我尝试使用Jinja2模块,但是出现以下错误:
KeyError:'%表示列表%中的项目'
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)
无法找出错误,如果还有其他方法,请告诉我!
答案 0 :(得分:0)
似乎您混淆了两个不同的过程。 完成任务的第一种方法是先构建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)