| 1 |
# ext/turbogears.py |
| 2 |
# Copyright 2006-2022 the Mako authors and contributors <see AUTHORS file> |
| 3 |
# |
| 4 |
# This module is part of Mako and is released under |
| 5 |
# the MIT License: http://www.opensource.org/licenses/mit-license.php |
| 6 |
|
| 7 |
from mako import compat |
| 8 |
from mako.lookup import TemplateLookup |
| 9 |
from mako.template import Template |
| 10 |
|
| 11 |
|
| 12 |
class 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_func |
| 18 |
self.extension = extension |
| 19 |
if not options: |
| 20 |
options = {} |
| 21 |
|
| 22 |
# Pull the options out and initialize the lookup |
| 23 |
lookup_options = {} |
| 24 |
for k, v in options.items(): |
| 25 |
if k.startswith("mako."): |
| 26 |
lookup_options[k[5:]] = v |
| 27 |
elif k in ["directories", "filesystem_checks", "module_directory"]: |
| 28 |
lookup_options[k] = v |
| 29 |
self.lookup = TemplateLookup(**lookup_options) |
| 30 |
|
| 31 |
self.tmpl_options = {} |
| 32 |
# transfer lookup args to template args, based on those available |
| 33 |
# in getargspec |
| 34 |
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 path |
| 43 |
if "/" not in templatename: |
| 44 |
templatename = ( |
| 45 |
"/" + templatename.replace(".", "/") + "." + self.extension |
| 46 |
) |
| 47 |
|
| 48 |
# Lookup template |
| 49 |
return self.lookup.get_template(templatename) |
| 50 |
|
| 51 |
def render( |
| 52 |
self, info, format="html", fragment=False, template=None # noqa |
| 53 |
): |
| 54 |
if isinstance(template, str): |
| 55 |
template = self.load_template(template) |
| 56 |
|
| 57 |
# Load extra vars func if provided |
| 58 |
if self.extra_vars_func: |
| 59 |
info.update(self.extra_vars_func()) |
| 60 |
|
| 61 |
return template.render(**info) |