Skip to content

Instantly share code, notes, and snippets.

@pricco
Created May 19, 2014 19:31
Show Gist options
  • Save pricco/dbdcb36cb3a362385d16 to your computer and use it in GitHub Desktop.
Save pricco/dbdcb36cb3a362385d16 to your computer and use it in GitHub Desktop.
Wrapper for loading templates from "templates" directories in the specified apps.
"""
Wrapper for loading templates from "templates" directories in the specified
apps.
>>> {% extends 'grappelli,admin:admin/change_list.html' %}
"""
import os
import sys
from django.apps import apps
from django.template.loaders import app_directories
from django.utils._os import safe_join
from django.utils import six
app_template_dirs_cache = {}
def get_app_template_dir(app_label):
if app_label not in app_template_dirs_cache:
app_template_dirs = []
app_config = apps.get_app_config(app_label)
if app_config.path:
template_dir = os.path.join(app_config.path, 'templates')
if os.path.isdir(template_dir):
if six.PY2:
fs_encoding = sys.getfilesystemencoding() or \
sys.getdefaultencoding()
template_dir = template_dir.decode(fs_encoding)
app_template_dirs.append(template_dir)
app_template_dirs_cache[app_label] = tuple(app_template_dirs)
return app_template_dirs_cache[app_label]
class Loader(app_directories.Loader):
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 ':' in template_name:
app_labels, template_name = template_name.split(':')
for app_label in app_labels.split(','):
for template_dir in get_app_template_dir(app_label):
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment