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