format strings or page tempaltes

Max M maxm at mxm.dk
Tue Jul 23 13:20:17 EDT 2002


Jeff Davis wrote:


> Is this possible with the string format syntax? If not, could someone 
> recommend a good template module or something similar?


If you are doing OO programming you should know the adapter pattern 
which is especially usefull for this kind of work.

Untested:

you have an object:

class Person:
     name = 'Douglas'
     age = 42
     books = 'hhg2tu'

and you want to create a view for this class in html.

Then you should create an adapter/wrapper for this class that represents 
it as html:

class HtmlViewAdapter:

     def __init__(self, obj):
         self._obj = obj

     def __getattr__(self):
         return getattr(self._obj)

     def __getitem__(self, key):
         itm = getattr(self, key)
         if callable(itm):
	    itm = itm()
         return itm

class PersonHtmlViewAdapter(HtmlViewAdapter):

     def name(self):
         return '<b>%s</b>' % self._obj.name

     def age(self):
         return '%.2i' % self._obj.age

     def __str__(self):
         # this is a neat trick!
         return '<span class="person">name: %(name)s, age: %(age)s, 
books: %(book)s</span>' % self


And you can then use it like:

person = Person()
personHtmlView = PersonHtmlViewAdapter(person)

print personHtmlView.name()
 >>> <b>Douglas</b>

print "The Persons name is: %(name)s" % personHtmlView
 >>> The Persons name is: <b>Douglas</b>

print 'famous book %(book)s' % personHtmlView
 >>> famous book hhg2tu

print personHtmlView
 >>> <span class="person">name: Douglas, age: 42, book: hhg2tu</span>'


You can also put all kind of escaping methods into your HtmlViewAdapter, 
then you can make shure that all of your strings allways are escaped etc.

I find that this is a really powerfull way of rendering html, and I 
don't really see the need for a templating language when using this pattern.


regards Max M




More information about the Python-list mailing list