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