Converted the HTML-generator to Python3.
[wrw.git] / wrw / sp / xhtml.py
CommitLineData
62551769
FT
1import xml.dom.minidom, io
2from . import cons as _cons
3from . import util
ff79cdbf
FT
4dom = xml.dom.minidom.getDOMImplementation()
5
62551769
FT
6ns = "http://www.w3.org/1999/xhtml"
7doctype = "-//W3C//DTD XHTML 1.1//EN"
8dtd = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
ff79cdbf
FT
9
10class htmlelement(_cons.element):
11 def __todoc__(self):
12 doc = dom.createDocument(None, None, None)
13 doc.appendChild(dom.createDocumentType("html", doctype, dtd))
14 doc.appendChild(self.__todom__(doc))
15 return doc
16
17def cons(ctx=None):
18 return _cons.constructor(ns, htmlelement, ctx)
19
20def head(title=None, css=None):
21 h = cons()
22 head = h.head
23 if title:
24 head(h.title(title))
62551769 25 if isinstance(css, str) or isinstance(css, bytes):
ff79cdbf
FT
26 head(h.link(rel="stylesheet", type="text/css", href=css))
27 elif css:
28 for ss in css:
29 head(h.link(rel="stylesheet", type="text/css", href=ss))
30 return head
31
32class htmlformatter(util.formatter):
62551769 33 allowshort = set(["br", "hr", "img", "input"])
ff79cdbf
FT
34 def element(self, el, **extra):
35 if el.name in self.allowshort:
36 super(htmlformatter, self).element(el, **extra)
37 else:
38 self.longtag(el, **extra)
39
40class htmlindenter(util.indenter, htmlformatter):
41 pass
42
43def forreq(req, tree):
44 # XXX: Use proper Content-Type for clients accepting it.
45 req.ohead["Content-Type"] = "text/html; charset=utf-8"
62551769 46 buf = io.StringIO()
ff79cdbf
FT
47 htmlindenter.output(buf, tree, doctype=(doctype, dtd), charset="utf-8")
48 return [buf.getvalue()]
49
50def xhtmlresp(callable):
51 def wrapper(req):
52 return forreq(req, callable(req))
53 return wrapper