better way than: myPage += 'more html' , ...
Max M
maxm at mxm.dk
Wed Jun 25 18:13:01 EDT 2003
#Gobo Borz wrote:
#> Thanks, that opens up a world of possibilities I haven't began to
#> explore. In general, I'm not fond of templating systems because of the
#> overhead, but it seems as your suggestion might be fast, since it uses
#> ordinary string substitution.
#
Often an adapter is a good choice:
class HtmlViewAdapter:
"""
Base class that Adapts any object to html output.
"""
def __init__(self, obj):
self._obj = obj
def __getattr__(self, attr):
"Returns values for the attributes"
return getattr(self._obj, attr)
def __getitem__(self, item):
"get attrs as items for use in string formatting templates"
value = getattr(self, item)
if callable(value):
return value()
else:
return value
import time
class SomeObject:
"The object we want displayed in html"
def __init__(self):
self.id = 42
self.now = time.localtime()
self.title = 'the title'
class SomeObjectHtmlView(HtmlViewAdapter):
"""
an adapter for the object, here you can fine adjust, format dates
etc.
"""
def title(self):
return self._obj.title.upper()
def now(self):
return time.strftime('%y:%m:%d %H-%M-%S',self._obj.now)
view = SomeObjectHtmlView(SomeObject())
print '<a href="%(id)s">%(title)s</a> <i>%(now)s</i>' % view
>>> <a href="42">THE TITLE</a> <i>03:06:26 00-12-16</i>
More information about the Python-list
mailing list