2007-07-23 12:45:01 +08:00
|
|
|
"""
|
|
|
|
Wrapper for loading templates from the filesystem.
|
|
|
|
"""
|
2005-09-29 23:06:53 +08:00
|
|
|
|
2014-11-12 01:59:49 +08:00
|
|
|
from django.core.exceptions import SuspiciousFileOperation
|
2015-04-25 03:35:30 +08:00
|
|
|
from django.template import Origin, TemplateDoesNotExist
|
2007-07-23 12:45:01 +08:00
|
|
|
from django.utils._os import safe_join
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2014-11-16 01:35:02 +08:00
|
|
|
from .base import Loader as BaseLoader
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
class Loader(BaseLoader):
|
|
|
|
|
2016-12-14 05:50:00 +08:00
|
|
|
def __init__(self, engine, dirs=None):
|
|
|
|
super(Loader, self).__init__(engine)
|
|
|
|
self.dirs = dirs
|
|
|
|
|
2015-02-24 23:17:17 +08:00
|
|
|
def get_dirs(self):
|
2016-12-14 05:50:00 +08:00
|
|
|
return self.dirs if self.dirs is not None else self.engine.dirs
|
2015-02-24 23:17:17 +08:00
|
|
|
|
2015-03-04 05:48:26 +08:00
|
|
|
def get_contents(self, origin):
|
|
|
|
try:
|
2017-01-19 05:05:41 +08:00
|
|
|
with open(origin.name, encoding=self.engine.file_charset) as fp:
|
2015-03-04 05:48:26 +08:00
|
|
|
return fp.read()
|
2017-01-25 23:13:08 +08:00
|
|
|
except FileNotFoundError:
|
|
|
|
raise TemplateDoesNotExist(origin)
|
2015-03-04 05:48:26 +08:00
|
|
|
|
2016-12-31 09:09:26 +08:00
|
|
|
def get_template_sources(self, template_name):
|
2009-12-14 20:08:23 +08:00
|
|
|
"""
|
2015-03-04 05:48:26 +08:00
|
|
|
Return an Origin object pointing to an absolute path in each directory
|
|
|
|
in template_dirs. For security reasons, if a path doesn't lie inside
|
|
|
|
one of the template_dirs it is excluded from the result set.
|
2009-12-14 20:08:23 +08:00
|
|
|
"""
|
2016-12-31 09:09:26 +08:00
|
|
|
for template_dir in self.get_dirs():
|
2009-12-14 20:08:23 +08:00
|
|
|
try:
|
2015-03-04 05:48:26 +08:00
|
|
|
name = safe_join(template_dir, template_name)
|
2014-11-12 01:59:49 +08:00
|
|
|
except SuspiciousFileOperation:
|
|
|
|
# The joined path was located outside of this template_dir
|
|
|
|
# (it might be inside another one, so this isn't fatal).
|
2015-03-04 05:48:26 +08:00
|
|
|
continue
|
|
|
|
|
|
|
|
yield Origin(
|
|
|
|
name=name,
|
|
|
|
template_name=template_name,
|
|
|
|
loader=self,
|
|
|
|
)
|