Added app_dirname 'genshi'.
[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     app_dirname = 'genshi'
8
9     def __init__(self, params):
10         params = params.copy()
11         options = params.pop('OPTIONS').copy()
12         super(GenshiEngine, self).__init__(params)
13         loader = genshi.template.TemplateLoader(self.template_dirs, auto_reload=options['auto_reload'])
14         self.loader = loader
15
16
17     def from_string(self, template_code):
18         try:
19             template = genshi.template.MarkupTemplate(template_code)
20             return GenshiTemplateWrapper(template)
21         except genshi.TemplateCompilationFailed as exc:
22             raise django.template.TemplateSyntaxError(exc.args)
23
24
25     def get_template(self, template_name):
26         try:
27             template = self.loader.load(template_name)
28             return GenshiTemplateWrapper(self.loader.get_template(template_name))
29         except genshi.TemplateNotFound as exc:
30             raise django.template.TemplateDoesNotExist(exc.args)
31         except genshi.TemplateCompilationFailed as exc:
32             raise django.template.TemplateSyntaxError(exc.args)
33
34
35 class GenshiTemplateWrapper(object):
36     def __init__(self, template):
37         self.template = template
38
39     def render(self, context=None, request=None):
40         if context is None:
41             context = {}
42         if request is not None:
43             context['request'] = request
44             context['csrf_input'] = csrf_input_lazy(request)
45             context['csrf_token'] = csrf_token_lazy(request)
46         stream = self.template.generate(dict=context)
47         return stream.render()