import pkg_resources import templatetools class ZPT(object): """ You can access other templates with here/template_name (which is a name, potentially dotted, relative to the current template). Or here/parent.parent.template_name (which is goes up two levels from the current template in this case) """ def __init__(self, extra_vars_func=None, options=None): """The standard constructor takes an 'extra_vars_func', which is a callable that is called for additional variables with each rendering. Options is a dictionary that provides options specific to template engines (encoding, for example). The options should be prefixed with the engine's scheme name to allow the same dictionary to be passed in to multiple engines without ill effects.""" self.extra_vars_func = extra_vars_func self.options = options or {} self._cached_templates = {} def load_template(self, templatename, relative_to=None): while templatename.startswith('parent.'): templatename = templatename[len('parent.'):] relative_to = '.'.join(relative_to.split('.')[:-1]) if relative_to is not None: templatename = relative_to + '.' + templatename if templatename in self._cached_templates: template = self._cached_templates[templatename] template.refresh() else: parts = templatename.split('.') module = '.'.join(parts[:-1]) base = parts[-1] + '.pt' filename = pkg_resources.resource_filename(module, base) here = templatetools.HereSpace(self.load_template, (module,)) template = templatetools.FilePageTemplate( filename, here, **self.options) return template def render(self, info, format="html", fragment=False, template=None): "Renders the template to a string using the provided info." if self.extra_vars_func: info = info.copy() info.update(self.extra_vars_func()) if isinstance(template, basestring): template = self.load_template(template) text = template(context=info) return text