2008-10-13

A simple HTML generator using python2.6s format method.

So, python2.6 got released a little bit ago, and the changes are looking pretty nice - no real surprise there. One of the new things is a "format" method for strings that is meant to replace the % operator. You can read more about it here.

I like it quite a bit compared to the % operator - it's clearer, and not much more verbose. I've been writing a lot of web-based stuff lately, and a lot of times I don't want a full templater, I just want to return a couple of tags with ids / classnames, maybe some nesting. This is very easy to pull off in a clear manner with the format operator (it wasn't much less clear before either really):


from string import Formatter
tag = Formatter()
tag_string = """<{tag} {attrs}>{contents}"""

def generate(items):
result = ""
for item in items:
if isinstance(item['contents'], list):
contents_string = generate(item['contents'])
item['contents'] = contents_string
result += tag.vformat(tag_string, None, item)
return result


From here it's really easy to write little functions to generate what you need - all you need to make is a dict. I'll be using this over the next few weeks, and I'll probably be improving it a bit, but so far it, combined with some dict-making functions for tags I generate often, has suited my html generation needs just fine.

No comments:

Post a Comment