Started working on genshi template engine integration.
authorPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 5 May 2015 18:19:46 +0000 (20:19 +0200)
committerPhilipp Spitzer <philipp@spitzer.priv.at>
Tue, 5 May 2015 18:19:46 +0000 (20:19 +0200)
alpenzoo_django/settings.py
django_template_backend_genshi/__init__.py [new file with mode: 0644]

index 35510a47742347003215c415e9f573f2f71f6557..ea69887f92c288a277c3d69d00f3331eee1f277f 100644 (file)
@@ -67,6 +67,14 @@ TEMPLATES = [
             ],
         },
     },
+    {
+        'BACKEND': 'django_template_backend_genshi',
+        'DIRS': [],
+        'APP_DIRS': True,
+        'OPTIONS': {
+            'auto_reload': True
+        },
+    },
 ]
 
 WSGI_APPLICATION = 'alpenzoo_django.wsgi.application'
diff --git a/django_template_backend_genshi/__init__.py b/django_template_backend_genshi/__init__.py
new file mode 100644 (file)
index 0000000..e204d10
--- /dev/null
@@ -0,0 +1,48 @@
+from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
+import django.template.backends.base
+import genshi.template
+
+
+class GenshiEngine(django.template.backends.base.BaseEngine):
+    # Name of the subdirectory containing the templates for this engine
+    # inside an installed application.
+
+    def __init__(self, params):
+        params = params.copy()
+        options = params.pop('OPTIONS').copy()
+        super(GenshiEngine, self).__init__(params)
+        loader = genshi.template.TemplateLoader(self.dirs + self.app_dirs, auto_reload=options['auto_reload'])
+        self.loader = loader
+
+
+    def from_string(self, template_code):
+        try:
+            template = genshi.template.MarkupTemplate(template_code)
+            return GenshiTemplateWrapper(template)
+        except genshi.TemplateCompilationFailed as exc:
+            raise django.template.TemplateSyntaxError(exc.args)
+
+
+    def get_template(self, template_name):
+        try:
+            template = self.loader.load(template_name)
+            return GenshiTemplateWrapper(self.loader.get_template(template_name))
+        except genshi.TemplateNotFound as exc:
+            raise django.template.TemplateDoesNotExist(exc.args)
+        except genshi.TemplateCompilationFailed as exc:
+            raise django.template.TemplateSyntaxError(exc.args)
+
+
+class GenshiTemplateWrapper(object):
+    def __init__(self, template):
+        self.template = template
+
+    def render(self, context=None, request=None):
+        if context is None:
+            context = {}
+        if request is not None:
+            context['request'] = request
+            context['csrf_input'] = csrf_input_lazy(request)
+            context['csrf_token'] = csrf_token_lazy(request)
+        stream = self.template.generate(dict=context)
+        return stream.render()