turbogears.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # ext/turbogears.py
  2. # Copyright (C) 2006-2016 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(object):
  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 = '/' + templatename.replace('.', '/') + '.' +\
  37. self.extension
  38. # Lookup template
  39. return self.lookup.get_template(templatename)
  40. def render(self, info, format="html", fragment=False, template=None):
  41. if isinstance(template, compat.string_types):
  42. template = self.load_template(template)
  43. # Load extra vars func if provided
  44. if self.extra_vars_func:
  45. info.update(self.extra_vars_func())
  46. return template.render(**info)