我想用 python 格式化我的 html 代码。
我的Python文件是:
titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
html_text = """<html>
<head>
<style type="text/css">
table { border-collapse: collapse;}
td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
</style>
</head>
<body>
<table width="100%" height="100%" border="5px">
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
</table>
</body>
</html> % (titles[0], titles[1], titles[2], titles[3], titles[4])"""
f = open('temp.html', 'w')
f.write(html_text)
f.close()
我想让这些 %s 成为标题[0]、标题[1]、标题[2]、标题[3]、标题[4]。
我怎样才能做到?
最佳答案
您可以使用一些template engine that mix logic into template .
示例为 jinja2 :
- 使用
pip install jinja2
安装
2 那么代码将是:
html_text = """<html>
<head>...</head>
<body>
<table width="100%" height="100%" border="5px">
{% for title in titles %}
<tr>
<td>{{title}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>"""
from jinja2 import Template
titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
my_templ = Template(html_text)
with open('temp.html', 'w') as f:
f.write(my_templ.render(titles=titles))
请注意,它可以灵活地处理可变长度的列表。 模板引擎用于 Web 框架。
关于python - 使用 Python 格式化 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54166647/