X-Git-Url: https://git.mdrn.pl/librarian.git/blobdiff_plain/a7133c06fd9738c11a2bf60b4fc09365d15da1d7..f20435fd054f9176b8f867cd85322697d242b493:/librarian/xmlutils.py diff --git a/librarian/xmlutils.py b/librarian/xmlutils.py index 819c9a4..9e921a2 100644 --- a/librarian/xmlutils.py +++ b/librarian/xmlutils.py @@ -26,7 +26,10 @@ class Xmill(object): if text is None: return None text = flt(text) - return text + # TODO: just work on the tree and let lxml handle escaping. + e = etree.Element("x") + e.text = text + return etree.tostring(e, encoding=unicode)[3:-4] def generate(self, document): """Generate text from node using handlers defined in class.""" @@ -39,7 +42,7 @@ class Xmill(object): """ # Here we can see how a decision not to return the modified map # leads to a need for a hack. - return reduce(lambda a, b: a.update(b) or a, self._options, defaultdict(lambda: False)) + return reduce(lambda a, b: a.update(b) or a, self._options, defaultdict(lambda: None)) @options.setter def options(self, opts): @@ -96,13 +99,13 @@ class Xmill(object): if handler is None: pre = [self.filter_text(element.text)] - post = [] + post = [self.filter_text(element.tail)] else: vals = handler(element) # depending on number of returned values, vals can be None, a value, or a tuple. # how poorly designed is that? 9 lines below are needed just to unpack this. if vals is None: - return [] + return [self.filter_text(element.tail)] else: if not isinstance(vals, tuple): return [vals, self.filter_text(element.tail)] @@ -117,16 +120,30 @@ class Xmill(object): return out -def tag(name, classes=None, **attrs): +def tag_open_close(name_, classes_=None, **attrs): + u"""Creates tag beginning and end. + + >>> tag_open_close("a", "klass", x=u"ą<") + (u'', u'') + + """ + if classes_: + if isinstance(classes_, (tuple, list)): classes_ = ' '.join(classes_) + attrs['class'] = classes_ + + e = etree.Element(name_) + e.text = " " + for k, v in attrs.items(): + e.attrib[k] = v + pre, post = etree.tostring(e, encoding=unicode).split(u"> <") + return pre + u">", u"<" + post + +def tag(name_, classes_=None, **attrs): """Returns a handler which wraps node contents in tag `name', with class attribute set to `classes' and other attributes according to keyword paramters """ - if classes: - if isinstance(classes, (tuple, list)): classes = ' '.join(classes) - attrs['class'] = classes - a = ''.join([' %s="%s"' % (k,v) for (k,v) in attrs.items()]) def _hnd(self, element): - return "<%s%s>" % (name, a), "" % name + return tag_open_close(name_, classes_, **attrs) return _hnd