Skip to content

mxm, IT's mad science

Sections
Personal tools
You are here: Home » Papers » tabelizer.py
Downloads
You can download mxm products here.

Due to it's technical and international nature, this section is in english.

Max M Has a blog too.

og er glad for mad

 

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='&nbsp;')

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>&nbsp;</td>
            </tal:block>
            <tal:block condition="python:cell != None">
              <td>
                <div tal:content="cell" />
              </td>
            </tal:block>
          </tal:block>
        </tr>
      </tal:block>
    </table>

Created by maxm
Last modified 2008-10-08 04:02 PM