python列表和变量到html模板

pha*_*s15 4 python template-engine

将输出列表和变量很好地输入HTML模板的最佳方法是什么?

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

template = '''<html>
<title>Attributes</title>
- a
- b
- c
</html>'''
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?

jco*_*ado 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']})
Run Code Online (Sandbox Code Playgroud)

这将打印:

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

  <li>a</li>

  <li>b</li>

  <li>c</li>

</ul>
</html>
Run Code Online (Sandbox Code Playgroud)

注意:这只是一个小例子,理想情况下,模板应该在一个单独的文件中,以保持单独的业务逻辑和表示.