recommended way of generating HTML from Python
Michele Simionato
michele.simionato at gmail.com
Mon Feb 21 00:56:20 EST 2005
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).
FWIW, here is a my version of the recipe (stripped down to the bare
essentials)
.def makeattr(dict_or_list_of_pairs):
. dic = dict(dict_or_list_of_pairs)
. return " ".join("%s=%r" % (k, dic[k]) for k in dic)
.class HTMLTag(object):
. def __getattr__(self, name):
. def tag(value, **attr):
. """value can be a string or a sequence of strings."""
. if hasattr(value, "__iter__"): # is iterable
. value = " ".join(value)
. return "<%s %s>%s</%s>\n" % (name, makeattr(attr), value,
name)
. return tag
# example:
.html = HTMLTag()
.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]
.html_header = [html.tr(html.th(el) for el in tableheader)]
.html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
.print html.table(html_header + html_table)
Michele Simionato
More information about the Python-list
mailing list