Created
March 15, 2011 21:52
-
-
Save hidde-jan/871567 to your computer and use it in GitHub Desktop.
Django template loader that allows for `namespaced` loading of templates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Wrapper for loading templates from "templates" directories in INSTALLED_APPS | |
packages, prefixed by the appname for namespacing. | |
This loader finds `appname/templates/index.html` when looking for something | |
of the form `appname/index.html`. | |
""" | |
from django.template import TemplateDoesNotExist | |
from django.template.loaders.app_directories import app_template_dirs, Loader as BaseAppLoader | |
class Loader(BaseAppLoader): | |
''' | |
Modified AppDirectory Template Loader that allows namespacing templates | |
with the name of their app, without requiring an extra subdirectory | |
in the form of `appname/templates/appname`. | |
''' | |
def load_template_source(self, template_name, template_dirs=None): | |
try: | |
app_name, template_path = template_name.split('/', 1) | |
except ValueError: | |
raise TemplateDoesNotExist(template_name) | |
if not template_dirs: | |
template_dirs = (d for d in app_template_dirs if | |
d.endswith('/%s/templates' % app_name)) | |
return iter(super(Loader, self).load_template_source(template_path, | |
template_dirs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK, here's what I wound up with. It's working with Django 1.8 and Python 2.7 (Markdown code highlighting doesn't work right with this much text):
############################
from django.template import TemplateDoesNotExist
from django.template.loaders.app_directories import get_app_template_dirs, Loader as BaseAppLoader
app_template_dirs = get_app_template_dirs('templates')
from os import sep
class Loader(BaseAppLoader):
########################
So things got squirrelly, due to all of the changes that were necessary to make admin work, and also, from the admin GUI, the Documentation and Change Password links to work. Alternatively, the code as I left it after my first comment above can work if in your TEMPLATES list in settings.py you put for the dict 'DIRS' key entry a listing of the admin, admindocs and auth template directories, such as:
But those paths being installation-specific, for now I'm sticking with the code of this comment.