Rework html.py to derive from list object

svn: r12213
This commit is contained in:
Gerald Britton 2009-03-04 21:25:18 +00:00
parent 5eb2cf728d
commit d5f1247325

View File

@ -23,16 +23,9 @@
""" """
HTML operations. HTML operations.
This module exports one class: This module exports one class and two functions.
class Html: HTML generator
""" """
#------------------------------------------------------------------------
#
# python modules
#
#------------------------------------------------------------------------
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -42,13 +35,14 @@ import sys
_XHTML1_STRICT = 'PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' \ _XHTML1_STRICT = 'PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' \
'\t"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' '\t"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"'
class Html(object): class Html(list):
""" """
HTML class. HTML class.
""" """
__slots__ = ['items','indent','inline','end'] __slots__ = ['items','indent','inline','end']
# #
def __init__(self, tag='html', *args, **keywargs): def __init__(self, tag='html', *args, **keywargs):
super(Html, self).__init__([])
attr, indent, close, inline = '', False, True, False attr, indent, close, inline = '', False, True, False
for keyw, arg in keywargs.iteritems(): for keyw, arg in keywargs.iteritems():
if keyw in ['indent', 'close', 'inline'] and arg in [True, False, None]: if keyw in ['indent', 'close', 'inline'] and arg in [True, False, None]:
@ -60,51 +54,55 @@ class Html(object):
else: else:
attr += ' %s="%s"' % (keyw, arg) attr += ' %s="%s"' % (keyw, arg)
# #
if tag[0] == '<':
self.items = (tag,)
self.indent = indent self.indent = indent
self.inline = inline self.inline = inline
self.end = None self.end = close
return
# #
if tag[0] == '<':
self += [tag]
self.end = None
else:
begin = '<%s%s%s>' % ( begin = '<%s%s%s>' % (
tag, tag,
attr, attr,
('' if close or close is None else ' /') ('' if close or close is None else ' /')
) )
self += [begin] + list(args)
super(Html, self).extend(['</%s>' % tag] if close else [])
# #
self.items = (begin,) + args def __add__(self, value):
self.end = '</%s>' % tag if close else None if isinstance(value, Html) or not hasattr(value, '__iter__'):
self.indent = indent value = [value]
self.inline = inline index = len(self) - 1 if self.end else 0
# self[index:index] = value
def __add__(self, data):
self.items += data if isinstance(data,tuple) else (data,)
return self return self
# #
append = extend = __add__ __iadd__ = append = extend = __add__
# #
def index(self,data): def replace(self, cur_value, value):
i = 0 self[self.index(cur_value)] = value
for item in self.items:
if item == data:
return i
i += 1
else:
import sys
raise ValueError, "Html.index: item not found", sys.exc_info()[2]
# #
def replace(self,data,newdata): def __sub__(self, value):
i = self.index(data) del self[self.index(value)]
self.items = self.items[:i] + (newdata,) + self.items[i+1:]
#
def __sub__(self, data):
i = self.index(data)
self.items = self.items[:i] + self.items[i+1:]
return self return self
#
__isub__ = remove = __sub__
# #
def _print(data): def _print(data):
print data print data
#
def __str__(self):
return '%s'*len(self) % tuple(self[:])
#
def __iter__(self):
for item in self[:]:
if isinstance(item, self.Html):
for sub_item in item:
yield sub_item
else:
yield item
#
iterkeys = itervalues = iteritems = __iter__
# #
def write(self, method=_print, tabs=''): def write(self, method=_print, tabs=''):
tabs += '\t' if self.indent else '' tabs += '\t' if self.indent else ''
@ -112,51 +110,34 @@ class Html(object):
method('%s%s' % (tabs,self)) method('%s%s' % (tabs,self))
# #
else: else:
for item in self.items: for item in self[:]:
if isinstance(item, self.__class__): if isinstance(item, Html):
item.write(tabs=tabs) item.write(tabs=tabs)
else: else:
method('%s%s' % (tabs, item)) method('%s%s' % (tabs, item))
if self.end is not None:
method('%s%s' % (tabs, self.end))
# #
def __str__(self): def addXML(self, version=1.0, encoding="UTF-8", standalone="no"):
return '%s'*len(self.items) % self.items + \ xml = XML(version=version, encoding=encoding, standalone=standalone)
(self.end or '') self.insert(0, xml)
# #
def __iter__(self): def addDOCTYPE(self, name='html', external_id=_XHTML1_STRICT, *args):
for item in self.items: doctype = DOCTYPE(name='html', external_id=_XHTML1_STRICT, *args)
if isinstance(item, self.__class__): if len(self) and self[0][:6] == '<?xml ':
for j in item: self.insert(1, doctype)
yield j
else: else:
yield item self.insert(0, doctype)
if self.end is not None:
yield self.end def XML(version=1.0, encoding="UTF-8", standalone="no"):
#
def XML(self,version=1.0, encoding="UTF-8", standalone="no"):
return '<?xml %s %s %s?>' % ( return '<?xml %s %s %s?>' % (
'version="%s"' % version, 'version="%s"' % version,
'encoding="%s"' % encoding, 'encoding="%s"' % encoding,
'standalone="%s"' % standalone 'standalone="%s"' % standalone
) )
#
def addXML(self,version=1.0, encoding="UTF-8", standalone="no"): def DOCTYPE(name='html', external_id=_XHTML1_STRICT, *args):
xml = self.XML(version=version, encoding=encoding, standalone=standalone)
self.items = (xml,) + self.items
#
def DOCTYPE(self,name='html', external_id=_XHTML1_STRICT, *args):
return '<!DOCTYPE %s %s%s>' % ( return '<!DOCTYPE %s %s%s>' % (
name, name,
external_id, external_id,
' %s'*len(args) % args ' %s'*len(args) % args
) )
#
def addDOCTYPE(self,name='html', external_id=_XHTML1_STRICT, *args):
doctype = self.DOCTYPE(name='html', external_id=_XHTML1_STRICT, *args)
if len(self.items) > 0 and self.items[0][:6] == '<?xml ':
self.items = self.items[:1] + (doctype,) + self.items[1:]
else:
self.items = (doctype,) + self.items