how to generate html table from "table" data?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Dec 28 04:44:01 EST 2007


Ricardo Aráoz a écrit :
> Bruno Desthuilliers wrote:
(snip)
>> FWIW, I just wrote a function generating an html table from a list 
>> of header and a list of rows. I wrote the most Q&D, straightforward, 
>> braindead way, it's 17 lines long, doesn't even need an import 
>> statement, and took me less than 2 minutes to write - that is, far less 
>> work than reading your post and answering it.
> 
> Hi.
> Bruno, could you please post those 17 lines?   I'm not actually doing HTML
> work but I would find it interesting going through your code.
> 
I'm afraid I throw that code away - as I said, this was braindead Q&D 
code, and certainly not even worth the time you'd spend reading it. But 
I can rewrite it if you want:

def generate_html_table(headers, rows):
     html = []

     if headers:
         html.append("<tr>")
         for header in headers:
             html.append("<th>%s</th>" % header)
         html.append("</tr>")

     if rows:
         for row in rows:
             html.append("<tr>")
             for cell in row:
                 html.append("<td>%s</td>" % cell)
             html.append("</tr>")

     if html:
         html  = ["<table>"] + html + ["</table>"]

     return "\n".join(html)


Nothing interesting here, as you can see. And if you're going to do 
anything serious in web development, you'll be better using a templating 
system anyway.



More information about the Python-list mailing list