The Simplest Template

Ready for the simplest templating utility ever?  I was trying to prepare some JSON data stored in a tree and needed some simple code to generate templated text.  Below is a wrapper for python’s string.Template class:

import string

class SimpleTemplate(string.Template):
   """ Takes a string template and a tuple or list of identifier names
   """
   def __init__(self, tmplt, names):
     super(SimpleTemplate, self).__init__(tmplt)
     for name in names:
       setattr(self, name, '')

   def substitute(self):
     """ Does recursive substitution for nested template objects
     """
     d = self.__dict__
     for k, v in d.iteritems():
       if isinstance(v, SimpleTemplate):
         d[k] = v.substitute(**v.__dict__)
     return self.safe_substitute(**d)

The coolest part is that you can pass in template objects as attributes and the code will do recursive substitutions.  If you want to test this out, include the following script at the bottom:

if __name__ == '__main__':
   # Sample template for some JSON data
   _open  = '{\n'
   _id    = 'id:${id}\n'
   _name  = 'name:${name}\n'
   _data  = 'data:${data}\n'
   _close = '}'

   tmplt = ''.join((_open, _id, _name, _data, _close))
   w = SimpleTemplate(tmplt, ('id','name','data'))
   w.name = 'My name is W'
   w.id = 'W has an ID of 4'
   w.oops = 'Extraneous identifiers are ignored'
   # Note that identifiers not explicitly set default
   # to the empty string
   print w.substitute(), '\n'
   # Template using docstrings
   tmplt2 = \
   """Hello $foo
   $bar
   """
   w2 = SimpleTemplate(tmplt2, ('foo', 'bar'))
   w2.foo = 'World!'
   w2.bar = 'Foo Bar to You!'
   print w2.substitute()

Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Slashdot
  • StumbleUpon
  • Technorati
  1. No comments yet.

  1. No trackbacks yet.