如何使用 Jinja2 将 Python 列表格式化为 HTML 列表?

How to format Python lists as an HTML list using Jinja2?

给定以下列表的元素,它们表示 table 的列:

table1 = [('January', ''),('February', '00'), ('October', ''), ('NaN', '0')]
table2 = [('July', '0'),('December', 'NaN')]

还有这个html基本模板:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
</head>
<body>

<h1>Table element 1</h1>

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>month</td>
    <td>amount</td>
  </tr>
</table>

<h2>This is the status X</h2>
<input type="checkbox" id="valn" name="valn" value="val_n"> Validate

</body>
</html>

用列表值填充模板 table 的最佳方法是什么?并扩展 table 结构以获得更多的列表(列)对。例如,对于上面的管列表,这应该是 html 模板的填充版本:

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    table, th, td {
      border: 1px solid black;
    }
    </style>
    </head>
    <body>
    
    <h1>Table element 1</h1>
    
    <table>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <td>January</td>
        <td></td>
      </tr>
      <tr>
        <td>February</td>
        <td>00</td>
      </tr>
      <tr>
        <td>October</td>
        <td></td>
      </tr>
      <tr>
        <td>NaN</td>
        <td>00</td>
      </tr>
    </table>
    
    <h2>This is the status A</h2>
    <form action="/action_page.php">
    <input type="checkbox" id="val1" name="val1" value="val_1"> Validate
    </form>
    
    <h1>Table element 2</h1>
    
    <table>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <td>July</td>
        <td>0</td>
      </tr>
      <tr>
        <td>December</td>
        <td>NaN</td>
      </tr>
    </table>
    
    <h2>This is the status B</h2>
    <input type="checkbox" id="val2" name="val2" value="val_2"> Validate
    
    </body>
    </html>

虽然我可以通过一些字符串操作来处理这个问题,但我认为使用 jinja 有一种更简洁的方法。但是,我不知道如何控制模板中的不同元素,例如 table 和复选框。对于两个和 n 个元组列表,知道如何获得上述输出吗?

更改模板文件:

{% for row in table1 %}
  <tr>
    <td>{{ row[0] }}</td>
    <td>{{ row[1] }}</td>
  </tr>
{% endfor %}

您可以使用这段代码对其进行格式化:

from jinja2 import Template

table1 = [('January', ''),('February', '00'), ('October', ''), ('NaN', '0')]

t = open('template_file.html', 'r').read()  
template = Template(t)
formatted_template = template.render(table1=table1)
print(formatted_template)

您可以从 Jinja documentation

了解更多

正如您在评论中所要求的(与@nenadp 的回答基本相同,因为它已被更正):

from jinja2 import Template


table1 = [('January', ''), ('February', '00'), ('October', ''), ('NaN', '0')]
table2 = [('July', '0'), ('December', 'NaN')]

table = table1 + table2 # Concatenate the two lists

template = Template("""
<table>
    <tr>
        <th>Month</th>
        <th>Savings</th>
    </tr>
    <tr>
    {% for row in table %}
        <tr>
            <td>{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
        </tr>
    {% endfor %}
</table>
""")

print(template.render(table=table))