2007-07-23 12:45:01 +08:00
|
|
|
"""
|
2009-04-02 09:55:49 +08:00
|
|
|
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
|
2007-07-23 12:45:01 +08:00
|
|
|
packages.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import os
|
2008-11-14 03:03:42 +08:00
|
|
|
import sys
|
2005-10-17 10:37:50 +08:00
|
|
|
|
2013-12-22 18:35:17 +08:00
|
|
|
from django.apps import app_cache
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.conf import settings
|
2010-11-27 13:47:30 +08:00
|
|
|
from django.template.base import TemplateDoesNotExist
|
2009-12-14 20:08:23 +08:00
|
|
|
from django.template.loader import BaseLoader
|
2007-07-23 12:45:01 +08:00
|
|
|
from django.utils._os import safe_join
|
2012-08-08 19:07:49 +08:00
|
|
|
from django.utils import six
|
2005-10-17 10:37:50 +08:00
|
|
|
|
|
|
|
# At compile time, cache the directories to search.
|
2013-09-02 18:06:32 +08:00
|
|
|
if six.PY2:
|
2012-08-08 19:07:49 +08:00
|
|
|
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
|
2005-10-17 10:37:50 +08:00
|
|
|
app_template_dirs = []
|
2013-12-19 22:57:23 +08:00
|
|
|
for app_config in app_cache.get_app_configs():
|
|
|
|
template_dir = os.path.join(app_config.path, 'templates')
|
2005-10-17 10:37:50 +08:00
|
|
|
if os.path.isdir(template_dir):
|
2013-09-02 18:06:32 +08:00
|
|
|
if six.PY2:
|
2012-08-08 19:07:49 +08:00
|
|
|
template_dir = template_dir.decode(fs_encoding)
|
|
|
|
app_template_dirs.append(template_dir)
|
2005-10-17 10:37:50 +08:00
|
|
|
|
|
|
|
# It won't change, so convert it to a tuple to save memory.
|
|
|
|
app_template_dirs = tuple(app_template_dirs)
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2009-12-14 20:08:23 +08:00
|
|
|
class Loader(BaseLoader):
|
|
|
|
is_usable = True
|
|
|
|
|
|
|
|
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:
|
|
|
|
template_dirs = app_template_dirs
|
|
|
|
for template_dir in template_dirs:
|
|
|
|
try:
|
|
|
|
yield safe_join(template_dir, template_name)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# The template dir name was a bytestring that wasn't valid UTF-8.
|
|
|
|
raise
|
|
|
|
except ValueError:
|
|
|
|
# The joined path was located outside of template_dir.
|
|
|
|
pass
|
|
|
|
|
|
|
|
def load_template_source(self, template_name, template_dirs=None):
|
|
|
|
for filepath in self.get_template_sources(template_name, template_dirs):
|
|
|
|
try:
|
2012-05-26 02:37:38 +08:00
|
|
|
with open(filepath, 'rb') as fp:
|
2012-05-05 20:01:38 +08:00
|
|
|
return (fp.read().decode(settings.FILE_CHARSET), filepath)
|
2009-12-14 20:08:23 +08:00
|
|
|
except IOError:
|
|
|
|
pass
|
2010-01-11 02:36:20 +08:00
|
|
|
raise TemplateDoesNotExist(template_name)
|