| 1 |
import string |
| 2 |
|
| 3 |
from django.core.exceptions import ImproperlyConfigured |
| 4 |
from django.template import Origin, TemplateDoesNotExist |
| 5 |
from django.utils.html import conditional_escape |
| 6 |
|
| 7 |
from .base import BaseEngine |
| 8 |
from .utils import csrf_input_lazy, csrf_token_lazy |
| 9 |
|
| 10 |
|
| 11 |
class TemplateStrings(BaseEngine): |
| 12 |
app_dirname = "template_strings" |
| 13 |
|
| 14 |
def __init__(self, params): |
| 15 |
params = params.copy() |
| 16 |
options = params.pop("OPTIONS").copy() |
| 17 |
if options: |
| 18 |
raise ImproperlyConfigured("Unknown options: {}".format(", ".join(options))) |
| 19 |
super().__init__(params) |
| 20 |
|
| 21 |
def from_string(self, template_code): |
| 22 |
return Template(template_code) |
| 23 |
|
| 24 |
def get_template(self, template_name): |
| 25 |
tried = [] |
| 26 |
for template_file in self.iter_template_filenames(template_name): |
| 27 |
try: |
| 28 |
with open(template_file, encoding="utf-8") as fp: |
| 29 |
template_code = fp.read() |
| 30 |
except FileNotFoundError: |
| 31 |
tried.append( |
| 32 |
( |
| 33 |
Origin(template_file, template_name, self), |
| 34 |
"Source does not exist", |
| 35 |
) |
| 36 |
) |
| 37 |
else: |
| 38 |
return Template(template_code) |
| 39 |
raise TemplateDoesNotExist(template_name, tried=tried, backend=self) |
| 40 |
|
| 41 |
|
| 42 |
class Template(string.Template): |
| 43 |
def render(self, context=None, request=None): |
| 44 |
if context is None: |
| 45 |
context = {} |
| 46 |
else: |
| 47 |
context = {k: conditional_escape(v) for k, v in context.items()} |
| 48 |
if request is not None: |
| 49 |
context["csrf_input"] = csrf_input_lazy(request) |
| 50 |
context["csrf_token"] = csrf_token_lazy(request) |
| 51 |
return self.safe_substitute(context) |