One of the best controls in Asp.Net is the repeater &¬†datalistcontrols – they let you simply create repeating columns / rows of whatever output you wished to show from a set of database records… No html required – just drop your bindings into the template object and you were good to go…

Django does this is a limited way with the in-template for / endfor tags, they also have the cycle tag to cycle through options, but sometimes you need to create¬†multi-column table (for example – an image gallery), which can’t be done with the templating tags since there’s no in-line python support.

So I created a short function which will create  table of any iterable object which can take a column-size number, a table class definition and a string template (using %s markers) to define how to display the object.

It’s a table (I know), and I’m sure it can be done with CSS and divs, but I’d rather not – so here it is, a quick and dirty python function to create an Asp.Net-style datalist:

# Creates repeating columned table of an object:
# format is a string with %s marker; tableclass is the
# class to assign the table
def repeater(cols, repeatme, tableclass, format):
    out = "<table class='" + tableclass + "'><tr>"
    rows = len(repeatme) / cols
       
    colcount = 0
    for item in repeatme:
        entry = format %str(item)
       
        if colcount < cols:
            out += "<td>"
            out += entry
            out += "</td>"
            colcount += 1
        else:
            out += "</tr><tr>"
            out += "<td>"
            out += entry
            out += "</td>"
            colcount = 0
           
    out += "</table>"
   
    return out

There is one downsize to this – you can’t set the attribute name to display – so if the data object you are iterating doesn’t have a default view then you’ll be in trouble.

I’d like to expand this code to make it better, so if there’s a good idea to modify this and create a worthwhile data control which takes attribute parameters I’d love to see it (I use datalists in Asp.Net like popcorn, would be nice to have a generic peice of code to use here)…

Enjoy!