codekingpro/portable-devtools
114k
1# ext/turbogears.py2# Copyright 2006-2024 the Mako authors and contributors <see AUTHORS file>3#4# This module is part of Mako and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php6 7from mako import compat8from mako.lookup import TemplateLookup9from mako.template import Template10 11 12class TGPlugin:13 14 """TurboGears compatible Template Plugin."""15 16 def __init__(self, extra_vars_func=None, options=None, extension="mak"):17 self.extra_vars_func = extra_vars_func18 self.extension = extension19 if not options:20 options = {}21 22 # Pull the options out and initialize the lookup23 lookup_options = {}24 for k, v in options.items():25 if k.startswith("mako."):26 lookup_options[k[5:]] = v27 elif k in ["directories", "filesystem_checks", "module_directory"]:28 lookup_options[k] = v29 self.lookup = TemplateLookup(**lookup_options)30 31 self.tmpl_options = {}32 # transfer lookup args to template args, based on those available33 # in getargspec34 for kw in compat.inspect_getargspec(Template.__init__)[0]:35 if kw in lookup_options:36 self.tmpl_options[kw] = lookup_options[kw]37 38 def load_template(self, templatename, template_string=None):39 """Loads a template from a file or a string"""40 if template_string is not None:41 return Template(template_string, **self.tmpl_options)42 # Translate TG dot notation to normal / template path43 if "/" not in templatename:44 templatename = (45 "/" + templatename.replace(".", "/") + "." + self.extension46 )47 48 # Lookup template49 return self.lookup.get_template(templatename)50 51 def render(52 self, info, format="html", fragment=False, template=None # noqa53 ):54 if isinstance(template, str):55 template = self.load_template(template)56 57 # Load extra vars func if provided58 if self.extra_vars_func:59 info.update(self.extra_vars_func())60 61 return template.render(**info)62 