James Tauber

journeyman of some

blog > 2006 > 05 > 13 >

Python Templates

Back in 2003, I was playing around with building templates in Python by taking advantage of a combination of dictionary-based string substitution and the ability to late bind dictionary values using __getitem__.

I posted some graded examples to the Python Web SIG at the time and tonight I dug them up and formatted them into HTML with colour syntax highlighting:

http://jtauber.com/2006/05/templates.html

UPDATE (2006-05-19): One of my Pythonista heros, Ian Bicking, suggests an alternative approach which I like a lot.

Categories:
prev « python » next

Comments (3)

Marc on May 16, 2006:

Have you looked at Cheetah? Looks like a pretty cool templating system.

http://cheetahtemplate.org/

Erik Wilsher on May 20, 2006:

One possible refinement to the __getitem__ and _process methods of DictinaryTemplate would be (I hope formatting doesnt ruin this):

def __getitem__(self, key):
return self._process(*key.split("|"))

def _process(self, arg, *pipefunc):
if arg in self.dict:
val = self.dict[arg]
else:
try:
val = getattr(self, arg)()
except TypeError:
raise KeyError(arg)
for func_name in pipefunc:
if func_name in self.dict:
func = self.dict[func_name]
else:
func = getattr(self, func_name)
val = func(val)
return val


This way you can have multiple pipes such as:

class UL_Template(DictionaryTemplate):
_template = """<ul>\n%(lst|lstupper|li)s\n</ul>"""

def lstupper(lst):
return [s.upper() for s in lst]
print UL_Template(lst=["foo", "bar", "baz", "biz"], li=LI_Template, lstupper=lstupper)

Stan on Feb. 13, 2007:

Have you looked at the Template class under string in the Python modules. How would your ideas integrate with that?
Created: May 13, 2006
Last Modified: May 19, 2006
Author: jtauber