2014-11-12 05:57:50 +08:00
|
|
|
import string
|
|
|
|
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2015-04-25 03:33:03 +08:00
|
|
|
from django.template import Origin, TemplateDoesNotExist
|
2014-11-12 05:57:50 +08:00
|
|
|
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)))
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(params)
|
2014-11-12 05:57:50 +08:00
|
|
|
|
|
|
|
def from_string(self, template_code):
|
|
|
|
return Template(template_code)
|
|
|
|
|
|
|
|
def get_template(self, template_name):
|
2015-04-25 03:33:03 +08:00
|
|
|
tried = []
|
2014-11-12 05:57:50 +08:00
|
|
|
for template_file in self.iter_template_filenames(template_name):
|
|
|
|
try:
|
2019-09-05 22:25:30 +08:00
|
|
|
with open(template_file, encoding='utf-8') as fp:
|
2014-11-12 05:57:50 +08:00
|
|
|
template_code = fp.read()
|
2017-01-25 23:13:08 +08:00
|
|
|
except FileNotFoundError:
|
|
|
|
tried.append((
|
|
|
|
Origin(template_file, template_name, self),
|
|
|
|
'Source does not exist',
|
|
|
|
))
|
2017-08-07 22:24:58 +08:00
|
|
|
else:
|
|
|
|
return Template(template_code)
|
|
|
|
raise TemplateDoesNotExist(template_name, tried=tried, backend=self)
|
2014-11-12 05:57:50 +08:00
|
|
|
|
|
|
|
|
|
|
|
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)
|