The awesomest simple template – part deux

Ok. So recently I posted some code for a simple templating utility that I wrote. I’ve done some refactoring and have an even cooler version. This version better extends the behavior of string.Template and I’ve found it to be far more intuitive to use.  Without further ado:

import string

class SimpleTemplate(string.Template):
   """
   Takes a string and either a dict or any other
   object with the __dict__ attribute. Attributes passed
   into the constructor can be overriden by manually setting
   attribute values on the template. For example:
   tmplt = 'my ${name}'
   fcn = lambda: True
   fcn.name = 'original name'
   sTemplate = SimpleTemplate(tmplt, fcn)
   fcn.name = 'new name' # not propagated
   sTemplate.name = 'new name' # overrides fcn.name
   sTemplate.substitute()
   """
   def __init__(self, tmplt, dct={}):
     super(SimpleTemplate, self).__init__(tmplt)
     if hasattr(dct, '__dict__'):
       dct = dct.__dict__
     for name, value in dct.iteritems():
       setattr(self, name, value)

   def substitute(self):
     """Performs iterative substitution for nested templates"""
     dct = self.__dict__
     for k, v in dct.iteritems():
       if isinstance(v, SimpleTemplate):
         dct[k] = v.safe_substitute(**v.__dict__)
     return self.safe_substitute(**dct)

Enjoy!

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

  1. No trackbacks yet.