1 | import re, inspect |
---|
2 | from mako.lookup import TemplateLookup |
---|
3 | from mako.template import Template |
---|
4 | |
---|
5 | class TGPlugin(object): |
---|
6 | """TurboGears compatible Template Plugin.""" |
---|
7 | |
---|
8 | def __init__(self, extra_vars_func=None, options=None, extension='mak'): |
---|
9 | self.extra_vars_func = extra_vars_func |
---|
10 | self.extension = extension |
---|
11 | if not options: |
---|
12 | options = {} |
---|
13 | |
---|
14 | # Pull the options out and initialize the lookup |
---|
15 | lookup_options = {} |
---|
16 | for k, v in options.iteritems(): |
---|
17 | if k.startswith('mako.'): |
---|
18 | lookup_options[k[5:]] = v |
---|
19 | elif k in ['directories', 'filesystem_checks', 'module_directory']: |
---|
20 | lookup_options[k] = v |
---|
21 | self.lookup = TemplateLookup(**lookup_options) |
---|
22 | |
---|
23 | self.tmpl_options = {} |
---|
24 | # transfer lookup args to template args, based on those available |
---|
25 | # in getargspec |
---|
26 | for kw in inspect.getargspec(Template.__init__)[0]: |
---|
27 | if kw in lookup_options: |
---|
28 | self.tmpl_options[kw] = lookup_options[kw] |
---|
29 | |
---|
30 | def load_template(self, templatename, template_string=None): |
---|
31 | """Loads a template from a file or a string""" |
---|
32 | if template_string is not None: |
---|
33 | return Template(template_string, **self.tmpl_options) |
---|
34 | # Translate TG dot notation to normal / template path |
---|
35 | if '/' not in templatename: |
---|
36 | templatename = '/' + templatename.replace('.', '/') + '.' + self.extension |
---|
37 | |
---|
38 | # Lookup template |
---|
39 | return self.lookup.get_template(templatename) |
---|
40 | |
---|
41 | def render(self, info, format="html", fragment=False, template=None): |
---|
42 | if isinstance(template, basestring): |
---|
43 | template = self.load_template(template) |
---|
44 | |
---|
45 | # Load extra vars func if provided |
---|
46 | if self.extra_vars_func: |
---|
47 | info.update(self.extra_vars_func()) |
---|
48 | |
---|
49 | return template.render(**info) |
---|
50 | |
---|