turbogears.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # ext/turbogears.py
  2. # Copyright 2006-2025 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. from mako import compat
  7. from mako.lookup import TemplateLookup
  8. from mako.template import Template
  9. class TGPlugin:
  10. """TurboGears compatible Template Plugin."""
  11. def __init__(self, extra_vars_func=None, options=None, extension="mak"):
  12. self.extra_vars_func = extra_vars_func
  13. self.extension = extension
  14. if not options:
  15. options = {}
  16. # Pull the options out and initialize the lookup
  17. lookup_options = {}
  18. for k, v in options.items():
  19. if k.startswith("mako."):
  20. lookup_options[k[5:]] = v
  21. elif k in ["directories", "filesystem_checks", "module_directory"]:
  22. lookup_options[k] = v
  23. self.lookup = TemplateLookup(**lookup_options)
  24. self.tmpl_options = {}
  25. # transfer lookup args to template args, based on those available
  26. # in getargspec
  27. for kw in compat.inspect_getargspec(Template.__init__)[0]:
  28. if kw in lookup_options:
  29. 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 = (
  37. "/" + templatename.replace(".", "/") + "." + self.extension
  38. )
  39. # Lookup template
  40. return self.lookup.get_template(templatename)
  41. def render(
  42. self, info, format="html", fragment=False, template=None # noqa
  43. ):
  44. if isinstance(template, str):
  45. template = self.load_template(template)
  46. # Load extra vars func if provided
  47. if self.extra_vars_func:
  48. info.update(self.extra_vars_func())
  49. return template.render(**info)