Python django.conf.settings.TEMPLATE_LOADERS Examples

The following are 7 code examples of django.conf.settings.TEMPLATE_LOADERS(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: __init__.py    From django-compat with MIT License 6 votes vote down vote up
def get_template_loaders():
    """
    Compatibility method to fetch the template loaders.
    Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
    """
    try:
        from django.template.engine import Engine
    except ImportError:  # Django < 1.8
        Engine = None

    if Engine:
        try:
            engine = Engine.get_default()
        except ImproperlyConfigured:
            loaders = []
        else:
            loaders = engine.template_loaders
    else:  # Django < 1.8
        from django.template.loader import find_template_loader
        loaders = [
            find_template_loader(loader_name)
            for loader_name in settings.TEMPLATE_LOADERS]
    return loaders 
Example #2
Source File: loader.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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_name in settings.TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            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, make_origin(display_name, loader, name, dirs))
        except TemplateDoesNotExist:
            pass
    raise TemplateDoesNotExist(name) 
Example #3
Source File: templates.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_all_templates(pattern='*.html', ignore_private=True):
    """
    Finds all Django templates matching given glob in all TEMPLATE_LOADERS

    :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_
                        to match

    .. important:: At the moment egg loader is not supported.
    """
    templates = []
    template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)
    for loader_name in template_loaders:
        module, klass = loader_name.rsplit('.', 1)
        if loader_name in (
            'django.template.loaders.app_directories.Loader',
            'django.template.loaders.filesystem.Loader',
        ):
            loader_class = getattr(import_module(module), klass)
            if getattr(loader_class, '_accepts_engine_in_init', False):
                loader = loader_class(Engine.get_default())
            else:
                loader = loader_class()
            for dir in loader.get_template_sources(''):
                for root, dirnames, filenames in os.walk(dir):
                    for basename in filenames:
                        if ignore_private and basename.startswith("_"):
                            continue
                        filename = os.path.join(root, basename)
                        rel_filename = filename[len(dir)+1:]
                        if fnmatch.fnmatch(filename, pattern) or \
                           fnmatch.fnmatch(basename, pattern) or \
                           fnmatch.fnmatch(rel_filename, pattern):
                            templates.append(rel_filename)
        else:
            LOGGER.debug('%s is not supported' % loader_name)
    return sorted(set(templates)) 
Example #4
Source File: loader.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def find_template_loader(loader):
    if isinstance(loader, (tuple, list)):
        loader, args = loader[0], loader[1:]
    else:
        args = []
    if isinstance(loader, six.string_types):
        module, attr = loader.rsplit('.', 1)
        try:
            mod = import_module(module)
        except ImportError as e:
            raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))
        try:
            TemplateLoader = getattr(mod, attr)
        except AttributeError as e:
            raise ImproperlyConfigured('Error importing template source loader %s: "%s"' % (loader, e))

        if hasattr(TemplateLoader, 'load_template_source'):
            func = TemplateLoader(*args)
        else:
            # Try loading module the old way - string is full path to callable
            if args:
                raise ImproperlyConfigured("Error importing template source loader %s - can't pass arguments to function-based loader." % loader)
            func = TemplateLoader

        if not func.is_usable:
            import warnings
            warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader)
            return None
        else:
            return func
    else:
        raise ImproperlyConfigured('Loader does not define a "load_template" callable template source loader') 
Example #5
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        if not self._templates:
            warnings.warn(
                "You haven't defined a TEMPLATES setting. You must do so "
                "before upgrading to Django 1.10. Otherwise Django will be "
                "unable to load templates.", RemovedInDjango110Warning)
            self._templates = [
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': settings.TEMPLATE_DIRS,
                    'OPTIONS': {
                        'allowed_include_roots': settings.ALLOWED_INCLUDE_ROOTS,
                        'context_processors': settings.TEMPLATE_CONTEXT_PROCESSORS,
                        'debug': settings.TEMPLATE_DEBUG,
                        'loaders': settings.TEMPLATE_LOADERS,
                        'string_if_invalid': settings.TEMPLATE_STRING_IF_INVALID,
                    },
                },
            ]

        templates = OrderedDict()
        backend_names = []
        for tpl in self._templates:
            tpl = tpl.copy()
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl['BACKEND'].rsplit('.', 2)[-2]
            except Exception:
                invalid_backend = tpl.get('BACKEND', '<not defined>')
                raise ImproperlyConfigured(
                    "Invalid BACKEND for a template engine: {}. Check "
                    "your TEMPLATES setting.".format(invalid_backend))

            tpl.setdefault('NAME', default_name)
            tpl.setdefault('DIRS', [])
            tpl.setdefault('APP_DIRS', False)
            tpl.setdefault('OPTIONS', {})

            templates[tpl['NAME']] = tpl
            backend_names.append(tpl['NAME'])

        counts = Counter(backend_names)
        duplicates = [alias for alias, count in counts.most_common() if count > 1]
        if duplicates:
            raise ImproperlyConfigured(
                "Template engine aliases aren't unique, duplicates: {}. "
                "Set a unique NAME for each engine in settings.TEMPLATES."
                .format(", ".join(duplicates)))

        return templates 
Example #6
Source File: utils.py    From openhgsenti with Apache License 2.0 4 votes vote down vote up
def templates(self):
        if self._templates is None:
            self._templates = settings.TEMPLATES

        if not self._templates:
            warnings.warn(
                "You haven't defined a TEMPLATES setting. You must do so "
                "before upgrading to Django 1.10. Otherwise Django will be "
                "unable to load templates.", RemovedInDjango110Warning)
            self._templates = [
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': settings.TEMPLATE_DIRS,
                    'OPTIONS': {
                        'allowed_include_roots': settings.ALLOWED_INCLUDE_ROOTS,
                        'context_processors': settings.TEMPLATE_CONTEXT_PROCESSORS,
                        'debug': settings.TEMPLATE_DEBUG,
                        'loaders': settings.TEMPLATE_LOADERS,
                        'string_if_invalid': settings.TEMPLATE_STRING_IF_INVALID,
                    },
                },
            ]

        templates = OrderedDict()
        backend_names = []
        for tpl in self._templates:
            tpl = tpl.copy()
            try:
                # This will raise an exception if 'BACKEND' doesn't exist or
                # isn't a string containing at least one dot.
                default_name = tpl['BACKEND'].rsplit('.', 2)[-2]
            except Exception:
                invalid_backend = tpl.get('BACKEND', '<not defined>')
                raise ImproperlyConfigured(
                    "Invalid BACKEND for a template engine: {}. Check "
                    "your TEMPLATES setting.".format(invalid_backend))

            tpl.setdefault('NAME', default_name)
            tpl.setdefault('DIRS', [])
            tpl.setdefault('APP_DIRS', False)
            tpl.setdefault('OPTIONS', {})

            templates[tpl['NAME']] = tpl
            backend_names.append(tpl['NAME'])

        counts = Counter(backend_names)
        duplicates = [alias for alias, count in counts.most_common() if count > 1]
        if duplicates:
            raise ImproperlyConfigured(
                "Template engine aliases aren't unique, duplicates: {}. "
                "Set a unique NAME for each engine in settings.TEMPLATES."
                .format(", ".join(duplicates)))

        return templates 
Example #7
Source File: views.py    From canvas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    from django.template import TemplateDoesNotExist
    from django.utils.safestring import mark_safe
    from django.conf import settings

    template_name = request.GET.get('template', None)
    if template_name is None:
        return HttpResponseBadRequest('"template" key is required')

    try: # Django 1.2 ...
        from django.template.loader import find_template_loader, make_origin
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            if loader is not None:
                loaders.append(loader)
        for loader in loaders:
            try:
                source, display_name = loader.load_template_source(template_name)
                origin = make_origin(display_name, loader, template_name, settings.TEMPLATE_DIRS)
                break
            except TemplateDoesNotExist:
                source = "Template Does Not Exist: %s" % (template_name,)
    except (ImportError, AttributeError): # Django 1.1 ...
        from django.template.loader import find_template_source
        source, origin = find_template_source(template_name)

    try:
        from pygments import highlight
        from pygments.lexers import HtmlDjangoLexer
        from pygments.formatters import HtmlFormatter

        source = highlight(source, HtmlDjangoLexer(), HtmlFormatter())
        source = mark_safe(source)
        source.pygmentized = True
    except ImportError:
        pass

    return render_to_response('debug_toolbar/panels/template_source.html', {
        'source': source,
        'template_name': template_name
    })