File: tidywidget.py

package info (click to toggle)
python-jtoolkit 0.7.8-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,436 kB
  • ctags: 2,536
  • sloc: python: 15,143; makefile: 20
file content (43 lines) | stat: -rw-r--r-- 1,484 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python

import tidy

def tidyhtml(html):
    """simply tidies up html code, returning xhtml"""
    if isinstance(html, unicode):
        html = html.encode("utf-8")
    html = tidy.parseString(html, output_xhtml=1, tidy_mark=0, input_encoding="utf8", output_encoding="utf8")
    html = str(html)
    return html

def tidywidget(widget):
    """gets clean xhtml source for the widget by passing through tidy"""
    divstart = "<div id='tidywidget'>"
    divend = '</div>'
    html = "<html><body>" + divstart + widget.gethtml() + divend + "</body></html>"
    html = tidyhtml(html)
    divpos = html.find(divstart)
    if divpos == -1:
      divpos = html.find(divstart.replace("'", '"'))
    if divpos == -1:
      raise ValueError("Error finding div in tidied html")
    divendpos = html.rfind(divend)
    if divendpos == -1:
      raise ValueError("Error finding div end in tidied html")
    return html[divpos+len(divstart):divendpos]

def htmlresult(widgetfunction):
    """decorator that calls widget.gethtml() on the results of its function"""
    def tidyfunction(*args, **kwargs):
      result = widgetfunction(*args, **kwargs)
      return result
    return tidyfunction

def tidyresult(widgetfunction):
    """decorator that calls tidy(widget.gethtml()) on the results of its function"""
    def tidyfunction(*args, **kwargs):
      result = widgetfunction(*args, **kwargs)
      cleanhtml = tidywidget(result)
      return cleanhtml
    return tidyfunction