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 05:36:41 +08:00
|
|
|
import io
|
|
|
|
|
2014-11-12 01:59:49 +08:00
|
|
|
from django.core.exceptions import SuspiciousFileOperation
|
2010-11-27 13:47:30 +08:00
|
|
|
from django.template.base import 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):
|
|
|
|
|
|
|
|
def get_template_sources(self, template_name, template_dirs=None):
|
|
|
|
"""
|
|
|
|
Returns the absolute paths to "template_name", when appended to each
|
|
|
|
directory in "template_dirs". Any paths that don't lie inside one of the
|
|
|
|
template dirs are excluded from the result set, for security reasons.
|
|
|
|
"""
|
|
|
|
if not template_dirs:
|
2014-11-21 04:27:56 +08:00
|
|
|
template_dirs = self.engine.dirs
|
2009-12-14 20:08:23 +08:00
|
|
|
for template_dir in template_dirs:
|
|
|
|
try:
|
|
|
|
yield 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).
|
2009-12-14 20:08:23 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
def load_template_source(self, template_name, template_dirs=None):
|
|
|
|
tried = []
|
|
|
|
for filepath in self.get_template_sources(template_name, template_dirs):
|
|
|
|
try:
|
2014-11-21 04:27:56 +08:00
|
|
|
with io.open(filepath, encoding=self.engine.file_charset) as fp:
|
2014-11-12 05:36:41 +08:00
|
|
|
return fp.read(), filepath
|
2009-12-14 20:08:23 +08:00
|
|
|
except IOError:
|
|
|
|
tried.append(filepath)
|
|
|
|
if tried:
|
|
|
|
error_msg = "Tried %s" % tried
|
|
|
|
else:
|
2014-11-21 04:27:56 +08:00
|
|
|
error_msg = ("Your template directories configuration is empty. "
|
|
|
|
"Change it to point to at least one template directory.")
|
2010-01-11 02:36:20 +08:00
|
|
|
raise TemplateDoesNotExist(error_msg)
|