2 from mako.lookup import TemplateLookup
3 from mako.template import Template
5 class TGPlugin(object):
6 """TurboGears compatible Template Plugin."""
8 def __init__(self, extra_vars_func=None, options=None, extension='mak'):
9 self.extra_vars_func = extra_vars_func
10 self.extension = extension
14 # Pull the options out and initialize the lookup
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']:
21 self.lookup = TemplateLookup(**lookup_options)
23 self.tmpl_options = {}
24 # transfer lookup args to template args, based on those available
26 for kw in inspect.getargspec(Template.__init__)[0]:
27 if kw in lookup_options:
28 self.tmpl_options[kw] = lookup_options[kw]
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
39 return self.lookup.get_template(templatename)
41 def render(self, info, format="html", fragment=False, template=None):
42 if isinstance(template, basestring):
43 template = self.load_template(template)
45 # Load extra vars func if provided
46 if self.extra_vars_func:
47 info.update(self.extra_vars_func())
49 return template.render(**info)