"Dr. Who" <go****@spiceaid.com> writes:
This seems clunky and my next step was going to be to define generic
functions which would generate the surrounding html tags only when
passed the proper argument. I was wondering if there was a better way
to do this with a standard Python library. It looked like formatter
might but that it also might be too low-level.
You could use something like this:
class HTMLFormatter:
def __init__(self, tag, contents=None, **kwargs):
self.tag = tag
self._content = contents
self.attrs = dict()
self._set_attrs(kwargs)
def _set_attrs(self, attrs):
self.attrs = attrs
if '_class' in self.attrs:
self.attrs['class'] = self.attrs['_class']
del self.attrs['_class']
def set_content(self, contents, **kwargs):
"""
Set content of HTML element to contents.
f = HTMLFormatter('a')
f.set_content('cat', href='http://www.cat.org')
str(f)
'<a href="http://www.cat.org">cat</a>' str(HTMLFormatter('td', 'cat'))
'<td>cat</td>' str(HTMLFormatter('p', 'kitty kit', _class='cat'))
'<p class="cat">kitty kit</p>' str(HTMLFormatter('br'))
'<br/>'
"""
self._content = contents
if kwargs:
self._set_attrs(kwargs)
def set_attribute(self, attr, val):
"""Set/update attribute 'attr' to 'val'."""
self.attrs[attr] = val
def add_content(self, contents):
"""Add content to element.
p = HTMLFormatter('p', 'name of the cat is ')
p.add_content('meow')
str(p)
'<p>name of the cat is meow</p>' p = HTMLFormatter('td')
p.add_content('cat')
str(p)
'<td>cat</td>'
"""
if self._content is None:
self._content = ''
self._content = "%s%s" % (self._content, str(contents))
def contents(self):
"""Get contents of object.
p = HTMLFormatter('p', 'nice doggy dog')
p.contents()
'nice doggy dog' p.add_content(HTMLFormatter('em', 'called wuff'))
p.contents()
'nice doggy dog<em>called wuff</em>'
"""
return self._content
def __str__(self):
open_tag = '%s' % self.tag
if self.attrs:
attrs = self.attrs.items()
attrs.sort()
attrs_str = ' '.join(['%s="%s"' % (k, v) \
for k,v in attrs])
open_tag = '%s %s' % (self.tag, attrs_str)
if self._content is not None:
return '<%s>%s</%s>' % (open_tag, self._content, self.tag)
else:
return '<%s/>' % open_tag
Doctest strings show examples how to use it. For serious HTML building stuff
it needs fiddling with, but should be handy for tiny projects.
--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!
$_ = '456476617264204d616a616b6172692c20612043687269737 469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";