python - 使用 Python 格式化 HTML

标签 python html

我想用 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 :

  1. 使用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/

相关文章:

python - 如何调试被覆盖的 sys.modules 条目?

python - Django Rest框架绕过嵌套关系中的实体

javascript - 有没有办法清除一行 session 存储?

javascript - 什么会导致 click() 方法失败?

html - css中的冲突

python - 计算有向图中的累积流量

python - 填充绘制线下的区域

python - 在 if 循环中添加到字典

html - 悬停时停止文本向下移动

html - 如何防止 CSS 动画在每个循环后重置