【问题标题】:How to make python list to html table如何将python列表制作成html表格
【发布时间】:2018-10-03 06:18:34
【问题描述】:

我有这个 python 列表

result =[('921', 36638, None, None, 'ron', '28-SEP', 'platform'),
('921', 36637, None, None, 'john', '28-SEP', 'platform')]

此列表中的值是动态的。但是表头始终是静态的。

Table header: 
Issue   Vers    created_on  Build   Author  Commit  Source_Name

我想改变这个 python 输出并制作成一个 HTML 表格。

这是我目前的工作

z = import result
s =open(z)

table=['<htm><body><table border="1">']
for line in s.splitlines():
    if not line.strip():
        continue
    table.append(r'<tr><td>{}</td><td>{}</td></tr>'.format(*line.split('--- ')))

table.append('</table></body></html>')
print ''.join(table)    

我对放置静态标题感到困惑。谢谢

【问题讨论】:

    标签: python html python-3.x


    【解决方案1】:

    这可能是 jinja 模板的情况:

    from jinja2 import Template
    
    t = Template('''
    <html>
      <body>
        <table border="1">
    
          <tr>
          {%- for col in header %}
            <td>{{col}}</td>
          {%- endfor %}
          </tr>
    
          {% for row in rows -%}
          <tr>
          {%- for col in row %}
            <td>{{col if col is not none else '' }}</td> 
          {%- endfor %}
          </tr>
          {% endfor %}
    
        </table>
      </body>
    </html>
    ''')
    
    
    header = 'Issue Vers created_on Build Author Commit Source_Name'.split()
    rows = [('921', 36638, None, None, 'ron', '28-SEP', 'platform'),
            ('921', 36637, None, None, 'john', '28-SEP', 'platform')]
    
    strg = t.render(header=header, rows=rows)
    

    如果您不想在表格中打印Nones,可以将{{col}} 替换为{{col if col is not none else '' }}

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2021-02-07
      • 1970-01-01
      • 2021-01-01
      • 2013-05-07
      • 1970-01-01
      • 2017-03-16
      • 2020-06-10
      • 2012-04-27
      相关资源
      最近更新 更多