将Python列表和变量嵌入HTML模板

4 投票
3 回答
13388 浏览
提问于 2025-04-17 10:22

如何将输出的列表和变量漂亮地放入HTML模板中,最好的方法是什么?

list = ['a', 'b', 'c']

template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''

有没有更简单的方法来做到这一点?

3 个回答

0

HTML不支持空白字符,这意味着:

'\n'.join(x for x in list) #won't work

你可以试试以下方法。

'<br>'.join(x for x in list)

否则,使用模板是个不错的选择!

5

你可能应该看看一些模板引擎。这里有一个完整的列表 在这里

在我看来,最受欢迎的有:

比如在 jinja2 中:

import jinja2

template= jinja2.Template("""
<html>
<title>Attributes</title>
<ul>
  {% for attr in attrs %}
  <li>{{attr}}</li>
  {% endfor %}
</ul>
</html>""")

print template.render({'attrs': ['a', 'b', 'c']})

这段代码会输出:

<html>
<title>Attributes</title>
<ul>

  <li>a</li>

  <li>b</li>

  <li>c</li>

</ul>
</html>

注意:这只是一个小例子,理想情况下,模板应该放在一个单独的文件中,以便将业务逻辑和展示分开。

3

如果你觉得模板引擎太复杂或者太重了,你可以试试下面这种方法:

list = ['a', 'b', 'c']
# Insert newlines between every element, with a * prepended
inserted_list = '\n'.join(['* ' + x for x in list])

template = '''<html>
<title>Attributes</title>
%s
</html>''' %(inserted_list)


>>> print template
<html>
<title>Attributes</title>
* a
* b
* c
</html>

撰写回答