Reputation: 23
I have a list made in Python called list_servers which has a list of servers.
I am trying to send an email within the python script that uses HTML to display the list in a readable manner, however, I cannot figure out how to use a for loop in HTML.
I have tried using the Jinja2 module however, I am getting the following error:
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)
Can't figure out the error and if there is another way, please let me know!
Upvotes: 2
Views: 2705
Reputation: 1
It worked like a charm. But there is a small catch. If there is a need to use the output for sending mails using SMTP modules then it may not work as MIMETEXT of SMTP will not understand the variable.
Upvotes: 0
Reputation: 500
It seemed you confuse two distinct procedures. A first way to complete your task is to build the html list before and then insert it within the whole html section:
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)
The above method used the Python built-in .format
function. It is valid for simple case as the one in the example. Yet, for more complex HTML construction, you may want to stick with jinja2 functionalities as indicated below:
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)
Upvotes: 2