blob: efb9f2c55e1657d4a0135f7da828376621be9e4b (
plain)
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
|
import os
import sys
from zope.component import queryUtility
from zope.component.interfaces import ComponentLookupError
from zope.component import getSiteManager
from zope.interface import classProvides
from zope.interface import implements
from webob import Response
from repoze.bfg.interfaces import IView
from repoze.bfg.interfaces import ITemplateFactory
class Z3CPTTemplateFactory(object):
classProvides(ITemplateFactory)
implements(IView)
def __init__(self, path):
from z3c.pt import PageTemplateFile
self.template = PageTemplateFile(path)
def __call__(self, *arg, **kw):
result = self.template.render(**kw)
response = Response(result)
return response
def package_path(package):
return os.path.abspath(os.path.dirname(package.__file__))
def registerTemplate(template, path):
try:
sm = getSiteManager()
except ComponentLookupError:
pass
else:
sm.registerUtility(template, IView, name=path)
def render_template(path, **kw):
# XXX use pkg_resources
if not os.path.isabs(path):
package_globals = sys._getframe(1).f_globals
package_name = package_globals['__name__']
package = sys.modules[package_name]
prefix = package_path(package)
path = os.path.join(prefix, path)
template = queryUtility(IView, path)
if template is None:
if not os.path.exists(path):
raise ValueError('Missing template file: %s' % path)
template = Z3CPTTemplateFactory(path)
registerTemplate(template, path)
return template(**kw)
|