Work-around to get compressor working for jinja2 templates in django 1.8.

Update JINJA2_GET_ENVIRONMENT() to retrieve correct environment for jinja2 backend.
This commit is contained in:
Nicholas Wilson 2015-12-23 12:47:56 -08:00 committed by Mathieu Pillard
parent 4674c13259
commit a5b31a1130
2 changed files with 54 additions and 33 deletions

View File

@ -2,6 +2,7 @@ from __future__ import unicode_literals
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template.utils import InvalidTemplateEngineError
from appconf import AppConf
@ -69,11 +70,22 @@ class CompressorConf(AppConf):
OFFLINE_MANIFEST = 'manifest.json'
# The Context to be used when TemplateFilter is used
TEMPLATE_FILTER_CONTEXT = {}
# Function that returns the Jinja2 environment to use in offline compression.
# Returns the Jinja2 environment to use in offline compression.
def JINJA2_GET_ENVIRONMENT():
alias = 'Jinja2'
try:
import jinja2
return jinja2.Environment()
from django.template.loader import _engine_list
engines = _engine_list(alias)
if engines:
engine = engines[0]
return engine.env
except InvalidTemplateEngineError:
raise InvalidTemplateEngineError(
"Could not find config for '{}' "
"in settings.TEMPLATES. "
"COMPRESS_JINJA2_GET_ENVIRONMENT() may "
"need to be defined in settings".format(alias))
except ImportError:
return None

View File

@ -12,8 +12,8 @@ from django.core.management.base import BaseCommand, CommandError
import django.template
from django.template import Context
from django.utils import six
from django.template.loader import get_template # noqa Leave this in to preload template locations
from django.template.utils import InvalidTemplateEngineError
from django.template import engines
from compressor.cache import get_offline_hexdigest, write_offline_manifest
@ -101,6 +101,7 @@ class Command(BaseCommand):
The result is cached with a cache-key derived from the content of the
compress nodes (not the content of the possibly linked files!).
"""
engine = options.get("engine", "django")
extensions = options.get('extensions')
extensions = self.handle_extensions(extensions or ['html'])
verbosity = int(options.get("verbosity", 0))
@ -110,34 +111,44 @@ class Command(BaseCommand):
raise OfflineGenerationError("No template loaders defined. You "
"must set TEMPLATE_LOADERS in your "
"settings.")
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(module,
'get_template_sources', None)
if get_template_sources is None:
get_template_sources = loader.get_template_sources
paths.update(str(origin) for origin in get_template_sources(''))
except (ImportError, AttributeError, TypeError):
# Yeah, this didn't work out so well, let's move on
pass
if not paths:
raise OfflineGenerationError("No template paths found. None of "
"the configured template loaders "
"provided template paths. See "
"https://docs.djangoproject.com/en/1.8/topics/templates/ "
"for more information on template "
"loaders.")
if verbosity > 1:
log.write("Considering paths:\n\t" + "\n\t".join(paths) + "\n")
templates = set()
for path in paths:
for root, dirs, files in os.walk(path,
followlinks=options.get('followlinks', False)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(fnmatch(name, "*%s" % glob) for glob in extensions))
if engine == 'django':
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(module,
'get_template_sources', None)
if get_template_sources is None:
get_template_sources = loader.get_template_sources
paths.update(str(origin) for origin in get_template_sources(''))
except (ImportError, AttributeError, TypeError):
# Yeah, this didn't work out so well, let's move on
pass
if not paths:
raise OfflineGenerationError("No template paths found. None of "
"the configured template loaders "
"provided template paths. See "
"https://docs.djangoproject.com/en/1.8/topics/templates/ "
"for more information on template "
"loaders.")
if verbosity > 1:
log.write("Considering paths:\n\t" + "\n\t".join(paths) + "\n")
for path in paths:
for root, dirs, files in os.walk(path,
followlinks=options.get('followlinks', False)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(fnmatch(name, "*%s" % glob) for glob in extensions))
elif engine == 'jinja2' and django.VERSION >= (1, 8):
env = settings.COMPRESS_JINJA2_GET_ENVIRONMENT()
if env and hasattr(env, 'list_templates'):
templates |= set([env.loader.get_source(env, template)[1] for template in
env.list_templates(filter_func=lambda _path:
os.path.splitext(_path)[-1] in extensions)])
if not templates:
raise OfflineGenerationError("No templates found. Make sure your "
"TEMPLATE_LOADERS and TEMPLATE_DIRS "
@ -145,9 +156,7 @@ class Command(BaseCommand):
if verbosity > 1:
log.write("Found templates:\n\t" + "\n\t".join(templates) + "\n")
engine = options.get("engine", "django")
parser = self.__get_parser(engine)
compressor_nodes = OrderedDict()
for template_name in templates:
try: