Ticket #24694: 24694.py

File 24694.py, 1.9 KB (added by Carl Meyer, 9 years ago)

implementation as a subclass of existing backend

Line 
1import sys
2
3from django.template.backends import jinja2 as jinja2backend
4from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
5from django.template import TemplateDoesNotExist, TemplateSyntaxError
6from django.utils.module_loading import import_string
7import jinja2
8import six
9
10
11class Jinja2Backend(jinja2backend.Jinja2):
12 def __init__(self, params):
13 self.context_processors = [
14 import_string(p)
15 for p in params['OPTIONS'].pop('context_processors', [])
16 ]
17 super(Jinja2Backend, self).__init__(params)
18
19 def from_string(self, template_code):
20 return Template(
21 self.env.from_string(template_code), self.context_processors)
22
23 def get_template(self, template_name):
24 try:
25 return Template(
26 self.env.get_template(template_name), self.context_processors)
27 except jinja2.TemplateNotFound as exc:
28 six.reraise(TemplateDoesNotExist, TemplateDoesNotExist(exc.args),
29 sys.exc_info()[2])
30 except jinja2.TemplateSyntaxError as exc:
31 six.reraise(TemplateSyntaxError, TemplateSyntaxError(exc.args),
32 sys.exc_info()[2])
33
34
35class Template(jinja2backend.Template):
36
37 def __init__(self, template, context_processors):
38 self.template = template
39 self.context_processors = context_processors
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 lazy_csrf_input = csrf_input_lazy(request)
47 context['csrf'] = lambda: lazy_csrf_input
48 context['csrf_input'] = lazy_csrf_input
49 context['csrf_token'] = csrf_token_lazy(request)
50 for cp in self.context_processors:
51 context.update(cp(request))
52 return self.template.render(context)
Back to Top