Code

Ticket #1586: virtual_app_directories.diff

File virtual_app_directories.diff, 2.4 KB (added by mir@…, 8 years ago)

patch to add contrib.template_loader.virtual_app_directories

Line 
1--- a/django/contrib/template_loader/virtual_app_directories.py
2+++ b/django/contrib/template_loader/virtual_app_directories.py
3@@ -0,0 +1,60 @@
4+"""
5+Wrapper for loading templates from "template" directories in installed app packages.
6+Different from the django provided app_directories, it creates a different template
7+namespace for each application. To use the template in your_app/templates/foo.html,
8+you specify 'your_app/foo'. Only the last app label is used as the namespace.
9+
10+Mostly shamelessly copied from django's app_directories template loader.
11+"""
12+
13+from django.conf import settings
14+from django.core.exceptions import ImproperlyConfigured
15+from django.template import TemplateDoesNotExist
16+from django.utils.datastructures import MultiValueDict
17+import os
18+
19+# At compile time, cache the directories to search.
20+app_template_dirs = MultiValueDict()
21+for app in settings.INSTALLED_APPS:
22+    i = app.rfind('.')
23+    if i == -1:
24+        m, a = app, None
25+    else:
26+        m, a = app[:i], app[i+1:]
27+    try:
28+        if a is None:
29+            mod = __import__(m, '', '', [])
30+            label = m
31+        else:
32+            mod = getattr(__import__(m, '', '', [a]), a)
33+            label = a
34+    except ImportError, e:
35+        raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0])
36+    template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
37+    if os.path.isdir(template_dir):
38+        app_template_dirs.appendlist(label, template_dir)
39+    print app_template_dirs
40+
41+def get_template_sources(template_name, template_dirs=None):
42+    # find top level directory component of template_name
43+    path = []
44+    head = template_name
45+    while True:
46+        head,tail=os.path.split(head)
47+        if not tail:
48+            break
49+        path.insert(0,tail)
50+    if len(path)<=1:
51+        return
52+    template_name = os.path.join(*path[1:])
53+    for template_dir in app_template_dirs.getlist(path[0]):
54+        yield os.path.join(template_dir, template_name) + settings.TEMPLATE_FILE_EXTENSION
55+
56+def load_template_source(template_name, template_dirs=None):
57+    for filepath in get_template_sources(template_name, template_dirs):
58+        try:
59+            return (open(filepath).read(), filepath)
60+        except IOError:
61+            print "Not found: %s" % filepath
62+    raise TemplateDoesNotExist, template_name
63+load_template_source.is_usable = True