August 27, 2006
Tabularize a list (e.g. for a website)
"""
Split a list of items into a table.
Example usage in a Kid/Genshi template (don't forget to add the tabularize
function as template variable):
<table>
<tr py:for="row in tabularize(users, 4, vertical=True)">
<td py:for="user in row">
<a py:if="user" href="/users/${user.id}">
${user.name}
</a>
</td>
</tr>
</table>
"""
def tabularize(items, columnCount, vertical=False):
"""Split a list of items into a table."""
rowCount = int(math.ceil(len(items) / float(columnCount)))
table = [[None] * columnCount for i in xrange(rowCount)]
for i, item in enumerate(items):
if vertical:
x, y = divmod(i, rowCount)
else:
y, x = divmod(i, columnCount)
table[int(y)][int(x)] = item
return table