~canonical-django/canonical-django/project-template

« back to all changes in this revision

Viewing changes to trunk/python-packages/django/template/loaders/app_directories.py

  • Committer: Matthew Nuzum
  • Date: 2008-11-13 05:46:03 UTC
  • Revision ID: matthew.nuzum@canonical.com-20081113054603-v0kvr6z6xyexvqt3
adding to version control

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
Wrapper for loading templates from "template" directories in INSTALLED_APPS
 
3
packages.
 
4
"""
 
5
 
 
6
import os
 
7
 
 
8
from django.conf import settings
 
9
from django.core.exceptions import ImproperlyConfigured
 
10
from django.template import TemplateDoesNotExist
 
11
from django.utils._os import safe_join
 
12
 
 
13
# At compile time, cache the directories to search.
 
14
app_template_dirs = []
 
15
for app in settings.INSTALLED_APPS:
 
16
    i = app.rfind('.')
 
17
    if i == -1:
 
18
        m, a = app, None
 
19
    else:
 
20
        m, a = app[:i], app[i+1:]
 
21
    try:
 
22
        if a is None:
 
23
            mod = __import__(m, {}, {}, [])
 
24
        else:
 
25
            mod = getattr(__import__(m, {}, {}, [a]), a)
 
26
    except ImportError, e:
 
27
        raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0])
 
28
    template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
 
29
    if os.path.isdir(template_dir):
 
30
        app_template_dirs.append(template_dir)
 
31
 
 
32
# It won't change, so convert it to a tuple to save memory.
 
33
app_template_dirs = tuple(app_template_dirs)
 
34
 
 
35
def get_template_sources(template_name, template_dirs=None):
 
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 ValueError:
 
42
            # The joined path was located outside of template_dir.
 
43
            pass
 
44
 
 
45
def load_template_source(template_name, template_dirs=None):
 
46
    for filepath in get_template_sources(template_name, template_dirs):
 
47
        try:
 
48
            return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
 
49
        except IOError:
 
50
            pass
 
51
    raise TemplateDoesNotExist, template_name
 
52
load_template_source.is_usable = True