tabelizer.py
I often need html tables generated from a list. I use this small library for that. I never seem to be able to find it on my harddisk, so here it is. Mostly for my own sake.
The Code:
"""
When doing automatic html table layout it is often usefull to have a tool
that can make "flowed" tables automatically.
"""
def tabelizer(sequence, nCols):
nItems = len(sequence)
table = []
nRows, remainder = divmod(nItems, nCols)
if remainder:
nRows += 1
for nRow in xrange(nRows):
row = []
for nCol in xrange(nCols):
try:
row.append(sequence[nRow*nCols+nCol])
except IndexError:
row.append(None)
table.append(row)
return table
def htmlTable(rows, tableTag='<table>', emptyVal=''):
result = [tableTag]
a = result.append
for row in rows:
a(' <tr>')
for col in row:
if col is None:
col = emptyVal
a(' <td>%s</td>' % str(col))
a(' </tr>')
a('</table>')
return '\n'.join(result)
if __name__ == '__main__':
testdata = range(1, 10+1)
for nCols in testdata:
table = tabelizer(testdata, nCols, )
print table
print htmlTable(table, emptyVal=' ')
If you want to make the tables in Zope Page Templates, then this is the general method:
<table border="1" width="100%">
<tal:block repeat="row python:here.tabelizer(range(1, 8), 3)">
<tr>
<tal:block repeat="cell row">
<tal:block condition="python:cell == None">
<td> </td>
</tal:block>
<tal:block condition="python:cell != None">
<td>
<div tal:content="cell" />
</td>
</tal:block>
</tal:block>
</tr>
</tal:block>
</table>