Last active
December 18, 2015 12:08
-
-
Save yuchant/5780139 to your computer and use it in GitHub Desktop.
Django Get Template Source
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
''' | |
Django doesn't ship with a way to use the template loading framework to output raw source. | |
It's kinda important since we use the framework to walk the template dirs | |
''' | |
import inspect | |
from django.conf import settings | |
from django.template.loader import find_template_loader | |
from django.template import TemplateDoesNotExist | |
template_source_loaders = None | |
def build_loaders(): | |
''' | |
Subclass existing loaders but modify to output uncompiled templates | |
''' | |
new_loaders = [] | |
for loader in settings.TEMPLATE_LOADERS: | |
loader_cls = find_template_loader(loader) | |
class SourceLoader(loader_cls.__class__): | |
def load_template(self, template_name, template_dirs=None): | |
source, display_name = self.load_template_source(template_name, template_dirs) | |
return source, display_name | |
new_loaders.append(SourceLoader()) | |
return new_loaders | |
def find_template(name, dirs=None): | |
# Calculate template_source_loaders the first time the function is executed | |
# because putting this logic in the module-level namespace may cause | |
# circular import errors. See Django ticket #1292. | |
global template_source_loaders | |
if template_source_loaders is None: | |
loaders = [] | |
for loader in build_loaders(): | |
if loader is not None: | |
loaders.append(loader) | |
template_source_loaders = tuple(loaders) | |
for loader in template_source_loaders: | |
try: | |
source, display_name = loader(name, dirs) | |
return source | |
except TemplateDoesNotExist: | |
pass | |
raise TemplateDoesNotExist(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment