~loggerhead-team/loggerhead/trunk-rich

« back to all changes in this revision

Viewing changes to turbosimpletal/zptsupport.py

  • Committer: Robey Pointer
  • Date: 2007-03-06 07:18:57 UTC
  • Revision ID: robey@lag.net-20070306071857-jqc8kphzcneb0bdd
add lsprof decorator; comment out unnecessary nbsp; conversion.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"TurboGears support for Zope Page Templates"
2
 
 
3
 
import StringIO
4
 
import os
5
 
import pkg_resources
6
 
 
7
 
from simpletal import simpleTAL, simpleTALES
8
 
 
9
 
 
10
 
_zpt_cache = {}
11
 
def zpt(tfile):
12
 
    tinstance = _zpt_cache.get(tfile)
13
 
    stat = os.stat(tfile)
14
 
    if tinstance is None or tinstance.stat != stat:
15
 
        tinstance = _zpt_cache[tfile] = TemplateWrapper(
16
 
            simpleTAL.compileXMLTemplate(open(tfile)), tfile, stat)
17
 
    return tinstance
18
 
 
19
 
 
20
 
class TemplateWrapper(object):
21
 
 
22
 
    def __init__(self, template, filename, stat):
23
 
        self.template = template
24
 
        self.filename = filename
25
 
        self.stat = stat
26
 
 
27
 
    def expand(self, **info):
28
 
        context = simpleTALES.Context(allowPythonPath=1)
29
 
        for k, v in info.iteritems():
30
 
            context.addGlobal(k, v)
31
 
        s = StringIO.StringIO()
32
 
        self.template.expandInline(context, s)
33
 
        return s.getvalue()
34
 
 
35
 
    def expand_(self, f, **info):
36
 
        context = simpleTALES.Context(allowPythonPath=1)
37
 
        for k, v in info.iteritems():
38
 
            context.addGlobal(k, v)
39
 
        self.template.expand(context, f, 'utf-8')
40
 
 
41
 
    @property
42
 
    def macros(self):
43
 
        return self.template.macros
44
 
 
45
 
 
46
 
class TurboZpt(object):
47
 
    extension = "pt"
48
 
 
49
 
    def __init__(self, extra_vars_func=None):
50
 
        self.get_extra_vars = extra_vars_func
51
 
 
52
 
    def load_template(self, classname, loadingSite=False):
53
 
        """Searches for a template along the Python path.
54
 
 
55
 
        Template files must end in ".pt" and be in legitimate packages.
56
 
        Templates are automatically checked for changes and reloaded as
57
 
        neccessary.
58
 
        """
59
 
        divider = classname.rfind(".")
60
 
        if divider > -1:
61
 
            package = classname[0:divider]
62
 
            basename = classname[divider+1:]
63
 
        else:
64
 
            raise ValueError, "All templates must be in a package"
65
 
 
66
 
        tfile = pkg_resources.resource_filename(
67
 
            package, "%s.%s" % (basename, self.extension))
68
 
        return zpt(tfile)
69