Fix: Use template dirs of the base class in GenshiEngine.
[toast/alpenzoo.git] / django_template_backend_genshi / __init__.py
1 from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
2 import django.template.backends.base
3 import genshi.template
4
5
6 class GenshiEngine(django.template.backends.base.BaseEngine):
7     # Name of the subdirectory containing the templates for this engine
8     # inside an installed application.
9
10     def __init__(self, params):
11         params = params.copy()
12         options = params.pop('OPTIONS').copy()
13         super(GenshiEngine, self).__init__(params)
14         loader = genshi.template.TemplateLoader(self.template_dirs, auto_reload=options['auto_reload'])
15         self.loader = loader
16
17
18     def from_string(self, template_code):
19         try:
20             template = genshi.template.MarkupTemplate(template_code)
21             return GenshiTemplateWrapper(template)
22         except genshi.TemplateCompilationFailed as exc:
23             raise django.template.TemplateSyntaxError(exc.args)
24
25
26     def get_template(self, template_name):
27         try:
28             template = self.loader.load(template_name)
29             return GenshiTemplateWrapper(self.loader.get_template(template_name))
30         except genshi.TemplateNotFound as exc:
31             raise django.template.TemplateDoesNotExist(exc.args)
32         except genshi.TemplateCompilationFailed as exc:
33             raise django.template.TemplateSyntaxError(exc.args)
34
35
36 class GenshiTemplateWrapper(object):
37     def __init__(self, template):
38         self.template = template
39
40     def render(self, context=None, request=None):
41         if context is None:
42             context = {}
43         if request is not None:
44             context['request'] = request
45             context['csrf_input'] = csrf_input_lazy(request)
46             context['csrf_token'] = csrf_token_lazy(request)
47         stream = self.template.generate(dict=context)
48         return stream.render()