From 86c75996f051e574c95b9b163dfbaf37b4b4c8c2 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Tue, 11 Nov 2014 22:57:50 +0100 Subject: [PATCH] Added dummy template backend. --- django/template/backends/dummy.py | 52 +++++++++++++++++++++++++++++++ django/template/backends/utils.py | 14 +++++++++ 2 files changed, 66 insertions(+) create mode 100644 django/template/backends/dummy.py create mode 100644 django/template/backends/utils.py diff --git a/django/template/backends/dummy.py b/django/template/backends/dummy.py new file mode 100644 index 0000000000..813a0cf560 --- /dev/null +++ b/django/template/backends/dummy.py @@ -0,0 +1,52 @@ +import io +import string + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.template import TemplateDoesNotExist +from django.utils.html import conditional_escape + +from .base import BaseEngine +from .utils import csrf_input_lazy, csrf_token_lazy + + +class TemplateStrings(BaseEngine): + + app_dirname = 'template_strings' + + def __init__(self, params): + params = params.copy() + options = params.pop('OPTIONS').copy() + if options: + raise ImproperlyConfigured( + "Unknown options: {}".format(", ".join(options))) + super(TemplateStrings, self).__init__(params) + + def from_string(self, template_code): + return Template(template_code) + + def get_template(self, template_name): + for template_file in self.iter_template_filenames(template_name): + try: + with io.open(template_file, encoding=settings.FILE_CHARSET) as fp: + template_code = fp.read() + except IOError: + continue + + return Template(template_code) + + else: + raise TemplateDoesNotExist(template_name) + + +class Template(string.Template): + + def render(self, context=None, request=None): + if context is None: + context = {} + else: + context = {k: conditional_escape(v) for k, v in context.items()} + if request is not None: + context['csrf_input'] = csrf_input_lazy(request) + context['csrf_token'] = csrf_token_lazy(request) + return self.safe_substitute(context) diff --git a/django/template/backends/utils.py b/django/template/backends/utils.py new file mode 100644 index 0000000000..8147bb4988 --- /dev/null +++ b/django/template/backends/utils.py @@ -0,0 +1,14 @@ +from django.middleware.csrf import get_token +from django.utils.functional import lazy +from django.utils.html import format_html +from django.utils.safestring import SafeText + + +def csrf_input(request): + return format_html( + '', + get_token(request)) + + +csrf_input_lazy = lazy(csrf_input, SafeText, str) +csrf_token_lazy = lazy(get_token, str)