Ziyad
Ziyad

Reputation: 157

How to make python list to html table

I have this python list

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

The values in this list are dynamic. However the table header is always static.

Table header: 
Issue   Vers    created_on  Build   Author  Commit  Source_Name

I want to change this python output and make into a HTML table.

This is my work so far

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)    

I am confused as to put the static header.Thanks

Upvotes: 2

Views: 572

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46849

this may be a case for a jinja template:

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)

if you do not want the Nones printed in your table, you can replace {{col}} with {{col if col is not none else '' }}.

Upvotes: 3

Related Questions