|
0
|
1 |
""" |
|
|
2 |
Wrapper for loading templates from "templates" directories in INSTALLED_APPS |
|
|
3 |
packages. |
|
|
4 |
""" |
|
|
5 |
|
|
|
6 |
import os |
|
|
7 |
import sys |
|
|
8 |
|
|
|
9 |
from django.conf import settings |
|
|
10 |
from django.core.exceptions import ImproperlyConfigured |
|
|
11 |
from django.template import TemplateDoesNotExist |
|
|
12 |
from django.utils._os import safe_join |
|
|
13 |
from django.utils.importlib import import_module |
|
|
14 |
|
|
|
15 |
# At compile time, cache the directories to search. |
|
|
16 |
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() |
|
|
17 |
app_template_dirs = [] |
|
|
18 |
for app in settings.INSTALLED_APPS: |
|
|
19 |
try: |
|
|
20 |
mod = import_module(app) |
|
|
21 |
except ImportError, e: |
|
|
22 |
raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0]) |
|
|
23 |
template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') |
|
|
24 |
if os.path.isdir(template_dir): |
|
|
25 |
app_template_dirs.append(template_dir.decode(fs_encoding)) |
|
|
26 |
|
|
|
27 |
# It won't change, so convert it to a tuple to save memory. |
|
|
28 |
app_template_dirs = tuple(app_template_dirs) |
|
|
29 |
|
|
|
30 |
def get_template_sources(template_name, template_dirs=None): |
|
|
31 |
""" |
|
|
32 |
Returns the absolute paths to "template_name", when appended to each |
|
|
33 |
directory in "template_dirs". Any paths that don't lie inside one of the |
|
|
34 |
template dirs are excluded from the result set, for security reasons. |
|
|
35 |
""" |
|
|
36 |
if not template_dirs: |
|
|
37 |
template_dirs = app_template_dirs |
|
|
38 |
for template_dir in template_dirs: |
|
|
39 |
try: |
|
|
40 |
yield safe_join(template_dir, template_name) |
|
|
41 |
except UnicodeDecodeError: |
|
|
42 |
# The template dir name was a bytestring that wasn't valid UTF-8. |
|
|
43 |
raise |
|
|
44 |
except ValueError: |
|
|
45 |
# The joined path was located outside of template_dir. |
|
|
46 |
pass |
|
|
47 |
|
|
|
48 |
def load_template_source(template_name, template_dirs=None): |
|
|
49 |
for filepath in get_template_sources(template_name, template_dirs): |
|
|
50 |
try: |
|
|
51 |
return (open(filepath).read().decode(settings.FILE_CHARSET), filepath) |
|
|
52 |
except IOError: |
|
|
53 |
pass |
|
|
54 |
raise TemplateDoesNotExist, template_name |
|
|
55 |
load_template_source.is_usable = True |