-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.py
73 lines (62 loc) · 2.41 KB
/
template.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import cherrypy
from genshi.core import Stream
from genshi.output import encode, get_serializer
from genshi.template import Context, TemplateLoader
from genshi.filters import Translator, Transformer
from genshi.filters.transform import StreamBuffer
import gettext
#trans = gettext.GNUTranslations(open("po/sv.mo"))
def template_loaded(template):
pass
#template.filters.insert(0, Translator(trans.ugettext))
# template.filters.insert(0, Translator(trans.ugettext))
loader = TemplateLoader(
os.path.join(os.path.dirname(__file__), 'templates'),
auto_reload=True,
callback=template_loaded
)
def output(filename, method='xhtml', encoding='utf-8', doctype=None, parent='main', loader=loader, **options):
"""Decorator for exposed methods to specify what template they should use
for rendering, and which serialization method and options should be
applied.
"""
def decorate(func):
def wrapper(*args, **kwargs):
cherrypy.thread_data.template = loader.load(filename)
cherrypy.thread_data.parent = parent
opt = options.copy()
# if no doctype is set, try to autodetect
# if doctype is False, skip doctype
# if doctype is set, use it
if doctype is None:
if method == 'html':
opt.setdefault('doctype', 'html')
if method == 'xhtml':
opt.setdefault('doctype', 'xhtml')
elif doctype is not False:
opt.setdefault('doctype', doctype)
serializer = get_serializer(method, **opt)
stream = func(*args, **kwargs)
if not isinstance(stream, Stream):
return stream
return encode(serializer(stream), method=serializer,
encoding=encoding)
return wrapper
return decorate
def render(*args, **kwargs):
"""Function to render the given data to the template specified via the
``@output`` decorator.
"""
if args:
assert len(args) == 1, \
'Expected exactly one argument, but got %r' % (args,)
template = loader.load(args[0])
else:
template = cherrypy.thread_data.template
ctxt = Context(url=cherrypy.url)
ctxt.push(kwargs)
ctxt['_'] = lambda x: x # trans.ugettext
return template.generate(ctxt)