Skip to content

Add support for Tempita templates #85

Open
wants to merge 7 commits into from
View
42 web/contrib/template.py
@@ -113,6 +113,48 @@ def __getattr__(self, name):
t = self._lookup.get_template(path)
return t.render
+class render_tempita:
+ """Rendering interface to Tempita templates.
+
+ Example:
+
+ render = render_tempita(['templates'])
+ render.hello(name='tempita')
+ """
+
+ extensions = {
+ '.html': ('HTMLTemplate', 'text/html; charset=utf-8'),
+ '.xhtml': ('HTMLTemplate', 'application/xhtml+xml; charset=utf-8'),
+ '.txt': ('Template', 'text/plain'),
+ }
+
+ def __init__(self, directories):
+ import tempita
+ self.directories = directories
+
+ def _get_template(self, name, from_template=None):
+ import tempita
+ for directory in self.directories:
+ for extension in self.extensions:
+ filename = os.path.join(directory, name + extension)
+ if os.path.exists(filename):
+ if not from_template:
+ from_template = getattr(tempita, self.extensions[extension][0])
+ template = from_template.from_filename(filename, get_template=self._get_template)
+ template.content_type = self.extensions[extension][1]
+ return template
+
+ def __getattr__(self, name):
+ template = self._get_template(name)
+ if not template:
+ raise AttributeError('Template "%s" not found.' % name)
+ def render(*args, **kwargs):
+ import web
+ if 'headers' in web.ctx and template.content_type:
+ web.header('Content-Type', template.content_type, unique=True)
+ return template.substitute(*args, **kwargs)
+ return render
+
class cache:
"""Cache for any rendering interface.
Something went wrong with that request. Please try again.