def test_get_template_loaders(self):
     tloaders, tdirs = get_template_loaders_dirs()
     fs_loader = find_template_loader(
         'django.template.loaders.filesystem.Loader')
     app_loader = find_template_loader(
         'django.template.loaders.app_directories.Loader')
     self.assertEqual(tloaders[0].__class__, fs_loader.__class__)
     self.assertEqual(tloaders[1].__class__, app_loader.__class__)
Exemplo n.º 2
0
def get_template_loaders_dirs():
    fs_loader_module = 'django.template.loaders.filesystem.Loader'
    app_loader_module = 'django.template.loaders.app_directories.Loader'
    loader_configs = set(flatten(settings.TEMPLATE_LOADERS))
    dirs = ()
    loaders = []
    if fs_loader_module in loader_configs:
        dirs += settings.TEMPLATE_DIRS
        loaders.append(find_template_loader(fs_loader_module))
    if app_loader_module in loader_configs:
        dirs += app_template_dirs
        loaders.append(find_template_loader(app_loader_module))
    return loaders, dirs
Exemplo n.º 3
0
def get_template_loaders_dirs():
    fs_loader_module = 'django.template.loaders.filesystem.Loader'
    app_loader_module = 'django.template.loaders.app_directories.Loader'
    loader_configs = set(flatten(settings.TEMPLATE_LOADERS))
    dirs = ()
    loaders = []
    if fs_loader_module in loader_configs:
        dirs += settings.TEMPLATE_DIRS
        loaders.append(find_template_loader(fs_loader_module))
    if app_loader_module in loader_configs:
        dirs += app_template_dirs
        loaders.append(find_template_loader(app_loader_module))
    return loaders, dirs
Exemplo n.º 4
0
def find_template_and_decorate(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.

    from django.template.loader import find_template_loader, make_origin
    from django.template import TemplateDoesNotExist
    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)

            # see if this template has a render method, and if so
            # decorate it to emit signals when rendering happens
            if hasattr(source, 'render'):
                if not hasattr(source.render, 'decorated'):

                    # this class has not been decorated yet...
                    source.__class__.render = render_decorator(
                        source.__class__.render)
                
            return (source, make_origin(display_name, loader, name, dirs))
        except TemplateDoesNotExist:
            pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 5
0
def find_template(name, dirs=None, override_level=1):
    # 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.
    from django.template.loader import template_source_loaders
    origin_override_level = override_level
    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:
            times = 1
            while True:
                source, display_name = loader(name, dirs, override_level=times)
                if override_level == 1:
                    return (source, make_origin(display_name, loader, name, dirs))
                else:
                    override_level -= 1
                    times += 1
        except TemplateDoesNotExist:
            pass
    if origin_override_level > 1:
        raise OverrideError("Cannot find the override template")
    else:
        raise TemplateDoesNotExist(name)
Exemplo n.º 6
0
def find_default_template(name, dirs=None):
    """
    Exclude the theme.template_loader
    So we can properly get the templates not part of any theme.
    """
    # 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 non_theme_source_loaders
    if non_theme_source_loaders is None:
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            if loader_name != 'theme.template_loaders.load_template_source':
                loader = find_template_loader(loader_name)
                if loader is not None:
                    loaders.append(loader)
        non_theme_source_loaders = tuple(loaders)
    for loader in non_theme_source_loaders[-1:]:
        try:
            source, display_name = loader(name, dirs)
            return (source, make_origin(display_name, loader, name, dirs))
        except TemplateDoesNotExist:
            pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 7
0
def find_default_template(name, dirs=None):
    """
    Exclude the theme.template_loader
    So we can properly get the templates not part of any theme.
    """
    # 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 non_theme_source_loaders
    if non_theme_source_loaders is None:
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            if loader_name != 'theme.template_loaders.load_template_source':
                loader = find_template_loader(loader_name)
                if loader is not None:
                    loaders.append(loader)
        non_theme_source_loaders = tuple(loaders)
    for loader in non_theme_source_loaders[-1:]:
        try:
            source, display_name = loader(name, dirs)
            return (source, make_origin(display_name, loader, name, dirs))
        except TemplateDoesNotExist:
            pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 8
0
def setup_jinja_environment():
    """
    Load jinja environment based on active django template loaders or
    settings.JINJA2_TEMPLATE_LOADERS override.

    Populate jinja global context with settings.JINJA2_GLOBAL_CONTEXT
    """
    template_dirs = []

    for loader_string in jinja2_settings.JINJA2_TEMPLATE_LOADERS:
        [
            template_dirs.append(x) for x in loader.find_template_loader(
                loader_string).get_template_sources('')
        ]

    kwargs = jinja2_settings.JINJA2_ENVIRONMENT_KWARGS.copy()
    kwargs.update({
        'loader': jinja2.FileSystemLoader(template_dirs),
        'extensions': jinja2_settings.JINJA2_EXTENSIONS,
    })

    env = jinja2.Environment(**kwargs)
    env.template_class = jinja2_settings.Jinja2DjangoTemplate

    try:
        for key, value in jinja2_settings.JINJA2_GLOBAL_CONTEXT.items():
            env.globals[key] = value
    except (ValueError, AttributeError), e:
        raise Exception(
            "Trouble applying setting 'JINJA2_GLOBALS': {0}".format(e))
Exemplo n.º 9
0
def load_template(content = 'plain', type = 'content'):
    template_dir =  getattr(settings, "ADMIN_SUBSCRIBE_TEMPLATE_DIR", "email")
    template = None
    if type == 'content':
        if content == 'plain':
            template_name = '{0}.{1}'.format(type,'txt')
        else:
            template_name = '{0}.{1}'.format(type,'html')
        template_path = template_dir + "/" + template_name

        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            try:
                loader = find_template_loader(loader_name)
            except :
                pass
            else:
                if loader is not None:
                    loaders.append(loader)
        template_source_loaders = tuple(loaders)
        for loader in template_source_loaders:
            try:
                template = loader.load_template_source(template_path)
                return template[0]
            except TemplateDoesNotExist:
                pass
    else:
        if content == 'plain':
            template = '{0}.{1}'.format(type,'txt')
        else:
            template = '{0}.{1}'.format(type,'html')
    return template
Exemplo n.º 10
0
    def loaders(self):
        if not self._cached_loaders:
            self._cached_loaders = [
                find_template_loader(loader) for loader in self._loaders
            ]

        return self._cached_loaders
Exemplo n.º 11
0
def setup_jinja_environment():
    """
    Load jinja environment based on active django template loaders or
    settings.JINJA2_TEMPLATE_LOADERS override.

    Populate jinja global context with settings.JINJA2_GLOBAL_CONTEXT
    """
    template_dirs = []

    for loader_string in jinja2_settings.JINJA2_TEMPLATE_LOADERS:
        [template_dirs.append(x) for x in loader.find_template_loader(loader_string).get_template_sources('')]

    kwargs = jinja2_settings.JINJA2_ENVIRONMENT_KWARGS.copy()
    kwargs.update({
        'loader': jinja2.FileSystemLoader(template_dirs),
        'extensions': jinja2_settings.JINJA2_EXTENSIONS,
    })

    env = jinja2.Environment(**kwargs)
    env.template_class = jinja2_settings.Jinja2DjangoTemplate

    try:
        for key, value in jinja2_settings.JINJA2_GLOBAL_CONTEXT.items():
            env.globals[key] = value
    except (ValueError, AttributeError), e:
        raise Exception("Trouble applying setting 'JINJA2_GLOBALS': {0}".format(e))
Exemplo n.º 12
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     cached_loaders = [
         find_template_loader(loader) for loader in self._loaders
     ]
     # Return cached_loaders to be stored atomically. Otherwise, another thread
     # could see an incomplete list. See #17303.
     return cached_loaders
Exemplo n.º 13
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     if not self._cached_loaders:
         cached_loaders = []
         for loader in self._loaders:
             cached_loaders.append(find_template_loader(loader))
         self._cached_loaders = cached_loaders
     return self._cached_loaders
Exemplo n.º 14
0
    def loaders(self):
        if not self._cached_loaders:
            self._cached_loaders = [
                find_template_loader(loader)
                for loader in self._loaders
            ]

        return self._cached_loaders
Exemplo n.º 15
0
 def __init__(self, *args, **kwargs):
     loaders = []
     for loader_name in settings.FLAVOURS_TEMPLATE_LOADERS:
         loader = find_template_loader(loader_name)
         if loader is not None:
             loaders.append(loader)
     self.template_source_loaders = tuple(loaders)
     super(BaseLoader, self).__init__(*args, **kwargs)
Exemplo n.º 16
0
 def test_missing_template_is_cached(self):
     "Check that the missing template is cached."
     template_loader = loader.find_template_loader(settings.TEMPLATE_LOADERS[0])
     # Empty cache, which may be filled from previous tests.
     template_loader.reset()
     # Check that 'missing.html' isn't already in cache before 'missing.html' is loaed
     self.assertRaises(KeyError, lambda: template_loader.template_cache["missing.html"])
     self.assertRaises(TemplateDoesNotExist, template_loader.load_template, "missing.html")
Exemplo n.º 17
0
    def initialize_type(cls, TEMPLATE_LOADERS=DEFAULT_TEMPLATE_LOADERS):
        cls.template_loaders = [
            find_template_loader(loader)
            for loader in TEMPLATE_LOADERS if loader]

        cls.add_to_class('filename', models.CharField(
            _('template'), max_length=100,
            choices=TemplateChoices(cls.template_loaders)))
Exemplo n.º 18
0
	def loaders(self):
		# Resolve loaders on demand to avoid circular imports
		if not self._cached_loaders:
			cached_loaders = []
			for loader in self._loaders:
				cached_loaders.append(find_template_loader(loader))
			self._cached_loaders = cached_loaders
		return self._cached_loaders
Exemplo n.º 19
0
 def __init__(self, *args, **kwargs):
     loaders = []
     for loader_name in settings.FLAVOURS_TEMPLATE_LOADERS:
         loader = find_template_loader(loader_name)
         if loader is not None:
             loaders.append(loader)
     self.template_source_loaders = tuple(loaders)
     super(BaseLoader, self).__init__(*args, **kwargs)
Exemplo n.º 20
0
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)

    # Allow downloading of template if 'download' GET arg is present.
    if request.GET.get('download', None):
        httpresp = HttpResponse(
            content=source,
            content_type="text/plain",
        )
        httpresp["Content-Disposition"] = 'attachment; filename={}'.format(
            os.path.split(template_name)[-1])
        return httpresp

    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
    })
Exemplo n.º 21
0
 def __init__(self, *args, **kwargs):
     loaders = []
     for loader_name in settings.TEMPLATE_LOADERS:
         if loader_name != 'cadocms.loaders.flavour.Loader':
             loader = find_template_loader(loader_name)
             if loader is not None:
                 loaders.append(loader)
     self.loaders = tuple(loaders)
     super(BaseLoader, self).__init__(*args, **kwargs)
Exemplo n.º 22
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     if not self._cached_loaders:
         for loader in self._loaders:
             if isinstance(loader, BaseLoader):
                 self._cached_loaders.append(loader)
             else:
                 self._cached_loaders.append(find_template_loader(loader))
     return self._cached_loaders
Exemplo n.º 23
0
 def __init__(self, *args, **kwargs):
     loaders = []
     for loader_name in settings.TEMPLATE_LOADERS:
         if loader_name != 'cadocms.loaders.flavour.Loader':
             loader = find_template_loader(loader_name)
             if loader is not None:
                 loaders.append(loader)
     self.loaders = tuple(loaders)
     super(BaseLoader, self).__init__(*args, **kwargs)
Exemplo n.º 24
0
def get_template_source_loaders():
    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)
    return template_source_loaders
Exemplo n.º 25
0
 def __init__(self, *args, **kwargs):
     loaders = []
     for loader_name in settings.TEMPLATE_LOADERS:
         if loader_name == 'mfw.template.loaders.flavour.Loader':
             continue
         loader = find_template_loader(loader_name)
         if loader is not None:
             loaders.append(loader)
     self.template_source_loaders = tuple(loaders)
     super(Loader, self).__init__(*args, **kwargs)
Exemplo n.º 26
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     if not self._cached_loaders:
         # Set self._cached_loaders atomically. Otherwise, another thread
         # could see an incomplete list. See #17303.
         cached_loaders = []
         for loader in self._loaders:
             cached_loaders.append(find_template_loader(loader))
         self._cached_loaders = cached_loaders
     return self._cached_loaders
Exemplo n.º 27
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     if not self._cached_loaders:
         # Set self._cached_loaders atomically. Otherwise, another thread
         # could see an incomplete list. See #17303.
         cached_loaders = []
         for loader in self._loaders:
             cached_loaders.append(find_template_loader(loader))
         self._cached_loaders = cached_loaders
     return self._cached_loaders
Exemplo n.º 28
0
 def test_missing_template_is_cached(self):
     "Check that the missing template is cached."
     template_loader = loader.find_template_loader(
         settings.TEMPLATE_LOADERS[0])
     # Empty cache, which may be filled from previous tests.
     template_loader.reset()
     # Check that 'missing.html' isn't already in cache before 'missing.html' is loaed
     self.assertRaises(
         KeyError, lambda: template_loader.template_cache["missing.html"])
     self.assertRaises(TemplateDoesNotExist, template_loader.load_template,
                       "missing.html")
Exemplo n.º 29
0
    def find_template(self, name, context, peeking=False):
        """
        Replacement for Django's ``find_template`` that uses the current
        template context to keep track of which template directories it
        has used when finding a template. This allows multiple templates
        with the same relative name/path to be discovered, so that
        circular template inheritance can occur.
        """

        # These imports want settings, which aren't available when this
        # module is imported to ``add_to_builtins``, so do them here.
        from django.template.loaders.app_directories import app_template_dirs
        from django.conf import settings

        # Store a dictionary in the template context mapping template
        # names to the lists of template directories available to
        # search for that template. Each time a template is loaded, its
        # origin directory is removed from its directories list.
        context_name = "OVEREXTENDS_DIRS"
        if context_name not in context:
            context[context_name] = {}
        if name not in context[context_name]:
            all_dirs = list(settings.TEMPLATE_DIRS) + list(app_template_dirs)
            # os.path.abspath is needed under uWSGI, and also ensures we
            # have consistent path separators across different OSes.
            context[context_name][name] = list(map(os.path.abspath, all_dirs))

        # Build a list of template loaders to use. For loaders that wrap
        # other loaders like the ``cached`` template loader, unwind its
        # internal loaders and add those instead.
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            loaders.extend(getattr(loader, "loaders", [loader]))

        # Go through the loaders and try to find the template. When
        # found, removed its absolute path from the context dict so
        # that it won't be used again when the same relative name/path
        # is requested.
        for loader in loaders:
            dirs = context[context_name][name]
            try:
                source, path = loader.load_template_source(name, dirs)
            except TemplateDoesNotExist:
                pass
            else:
                # Only remove the absolute path for the initial call in
                # get_parent, and not when we're peeking during the
                # second call.
                if not peeking:
                    remove_path = os.path.abspath(path[:-len(name) - 1])
                    context[context_name][name].remove(remove_path)
                return Template(source)
        raise TemplateDoesNotExist(name)
Exemplo n.º 30
0
    def find_template(self, name, context, peeking=False):
        """
        Replacement for Django's ``find_template`` that uses the current
        template context to keep track of which template directories it
        has used when finding a template. This allows multiple templates
        with the same relative name/path to be discovered, so that
        circular template inheritance can occur.
        """

        # These imports want settings, which aren't available when this
        # module is imported to ``add_to_builtins``, so do them here.
        from django.template.loaders.app_directories import app_template_dirs
        from django.conf import settings

        # Store a dictionary in the template context mapping template
        # names to the lists of template directories available to
        # search for that template. Each time a template is loaded, its
        # origin directory is removed from its directories list.
        context_name = "OVEREXTENDS_DIRS"
        if context_name not in context:
            context[context_name] = {}
        if name not in context[context_name]:
            all_dirs = list(settings.TEMPLATE_DIRS) + list(app_template_dirs)
            # os.path.abspath is needed under uWSGI, and also ensures we
            # have consistent path separators across different OSes.
            context[context_name][name] = map(os.path.abspath, all_dirs)

        # Build a list of template loaders to use. For loaders that wrap
        # other loaders like the ``cached`` template loader, unwind its
        # internal loaders and add those instead.
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            loaders.extend(getattr(loader, "loaders", [loader]))

        # Go through the loaders and try to find the template. When
        # found, removed its absolute path from the context dict so
        # that it won't be used again when the same relative name/path
        # is requested.
        for loader in loaders:
            dirs = context[context_name][name]
            try:
                source, path = loader.load_template_source(name, dirs)
            except TemplateDoesNotExist:
                pass
            else:
                # Only remove the absolute path for the initial call in
                # get_parent, and not when we're peeking during the
                # second call.
                if not peeking:
                    remove_path = os.path.abspath(path[:-len(name) - 1])
                    context[context_name][name].remove(remove_path)
                return Template(source)
        raise TemplateDoesNotExist(name)
Exemplo n.º 31
0
def get_template_loaders():
    """Compatibility method to fetch the template loaders."""
    if Engine:
        try:
            engine = Engine.get_default()
        except ImproperlyConfigured:
            loaders = []
        else:
            loaders = engine.template_loaders
    else:  # Django < 1.8
        loaders = [find_template_loader(loader_name) for loader_name in settings.TEMPLATE_LOADERS]
    return loaders
Exemplo n.º 32
0
def get_template_loaders():
    """Compatibility method to fetch the template loaders."""
    if Engine:
        try:
            engine = Engine.get_default()
        except ImproperlyConfigured:
            loaders = []
        else:
            loaders = engine.template_loaders
    else:  # Django < 1.8
        loaders = [find_template_loader(loader_name) for loader_name in settings.TEMPLATE_LOADERS]
    return loaders
Exemplo n.º 33
0
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)

    # Allow downloading of template if 'download' GET arg is present.
    if request.GET.get('download', None):
        httpresp = HttpResponse(content=source, content_type="text/plain", )
        httpresp["Content-Disposition"] = 'attachment; filename={}'.format(os.path.split(template_name)[-1])
        return httpresp

    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
    })
Exemplo n.º 34
0
def find_template_source(name):
    """
    Load the source code and origin of the first template that matches the
    given name.
    """
    for loader_path in settings.TEMPLATE_LOADERS:
        template_loader = loader.find_template_loader(loader_path)
        try:
            source, origin = template_loader.load_template_source(name)
        except TemplateDoesNotExist:
            continue
        break
    return source, origin
Exemplo n.º 35
0
def get_raw_template(name):
    """
    Uses Django's template loaders to find and return the
    raw template source. 
    """
    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is not None:
            try:
                return loader.load_template_source(name)[0]
            except TemplateDoesNotExist:
                pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 36
0
def get_raw_template(name):
    """
    Uses Django's template loaders to find and return the
    raw template source. 
    """
    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is not None:
            try:
                return loader.load_template_source(name)[0]
            except TemplateDoesNotExist:
                pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 37
0
 def test_missing_template_is_cached(self):
     "#19949 -- Check that the missing template is cached."
     template_loader = loader.find_template_loader(settings.TEMPLATE_LOADERS[0])
     # Empty cache, which may be filled from previous tests.
     template_loader.reset()
     # Check that 'missing.html' isn't already in cache before 'missing.html' is loaded
     self.assertRaises(KeyError, lambda: template_loader.template_cache["missing.html"])
     # Try to load it, it should fail
     self.assertRaises(TemplateDoesNotExist, template_loader.load_template, "missing.html")
     # Verify that the fact that the missing template, which hasn't been found, has actually
     # been cached:
     self.assertEqual(template_loader.template_cache.get("missing.html"),
                      TemplateDoesNotExist,
                      "Cached template loader doesn't cache file lookup misses. It should.")
Exemplo n.º 38
0
def get_template(template_name):
    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:
            return loader.load_template_source(template_name)
        except TemplateDoesNotExist:
            pass

    return ["", ""]
Exemplo n.º 39
0
 def loaders(self):
     # Resolve loaders on demand to avoid circular imports
     if not self._cached_loaders:
         for loader in self._loaders:
             loader = find_template_loader(loader)
             
             class InnerLoader(loader.__class__):
                 is_usable = True
                 def load_template_source(self, *args, **kwargs):
                     src = super(InnerLoader, self).load_template_source(*args, **kwargs)
                     return (shpaml.convert_text(src[0]), src[1])
             
             self._cached_loaders.append(InnerLoader())
     return self._cached_loaders
Exemplo n.º 40
0
 def test_missing_template_is_cached(self):
     "#19949 -- Check that the missing template is cached."
     template_loader = loader.find_template_loader(settings.TEMPLATE_LOADERS[0])
     # Empty cache, which may be filled from previous tests.
     template_loader.reset()
     # Check that 'missing.html' isn't already in cache before 'missing.html' is loaded
     self.assertRaises(KeyError, lambda: template_loader.template_cache["missing.html"])
     # Try to load it, it should fail
     self.assertRaises(TemplateDoesNotExist, template_loader.load_template, "missing.html")
     # Verify that the fact that the missing template, which hasn't been found, has actually
     # been cached:
     self.assertEqual(template_loader.template_cache.get("missing.html"),
                      TemplateDoesNotExist,
                      "Cached template loader doesn't cache file lookup misses. It should.")
Exemplo n.º 41
0
def find_template_source(name, dirs=None):
    """Custom version of find_template_source for Django >= 1.3, since
    find_template now always returns a compiled Template instance."""
    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(name, dirs)
            return (source, make_origin(display_name, loader, name, dirs))
        except TemplateDoesNotExist:
            pass
    raise TemplateDoesNotExist(name)
Exemplo n.º 42
0
def find_template(name, dirs=None):
    if django_template_loader.template_source_loaders is None:
        loaders = []
        for loader_name in settings.TEMPLATE_LOADERS:
            loader = django_template_loader.find_template_loader(loader_name)
            if loader is not None:
                loaders.append(loader)
        django_template_loader.template_source_loaders = tuple(loaders)
    for loader in django_template_loader.template_source_loaders:
        try:
            source, display_name = loader.load_template_source(name, dirs)
            return source, display_name
        except django_template_loader.TemplateDoesNotExist:
            pass
    raise django_template_loader.TemplateDoesNotExist(name)
Exemplo n.º 43
0
 def fetch_template_source_loaders(self):
     """
     Reads Django's TEMPLATE_LOADERS setting and fetches each
     template loader.
     """
     # grab Django's settings and the template loader loader
     from django.conf import settings
     from django.template.loader import find_template_loader
         # fetch template source loaders
     loaders = []
     for loader_name in settings.TEMPLATE_LOADERS:
         loader = find_template_loader(loader_name)
         if loader is not None:
             loaders.append(loader)
     return tuple(loaders)
Exemplo n.º 44
0
def get_template_source(template_name):
    """
    Return the source code of a template (not a compiled version)
    FIXME: Is there no django API for this?
    """
    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is None:
            continue
        try:
            template_source = loader.load_template_source(template_name)[0]
        except TemplateDoesNotExist:
            continue
        else:
            return template_source
    raise TemplateDoesNotExist(template_name)
Exemplo n.º 45
0
    def loaders(self):
        # Resolve loaders on demand to avoid circular imports
        if not self._cached_loaders:
            for loader in self._loaders:
                loader = find_template_loader(loader)

                class InnerLoader(loader.__class__):
                    is_usable = True

                    def load_template_source(self, *args, **kwargs):
                        src = super(InnerLoader, self).load_template_source(
                            *args, **kwargs)
                        return (shpaml.convert_text(src[0]), src[1])

                self._cached_loaders.append(InnerLoader())
        return self._cached_loaders
Exemplo n.º 46
0
def get_template_source(template_name):
    """
    Return the source code of a template (not a compiled version)
    FIXME: Is there no django API for this?
    """
    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is None:
            continue
        try:
            template_source = loader.load_template_source(template_name)[0]
        except TemplateDoesNotExist:
            continue
        else:
            return template_source
    raise TemplateDoesNotExist(template_name)
Exemplo n.º 47
0
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
Exemplo n.º 48
0
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)
            except TemplateDoesNotExist:
                source = "Template Does Not Exist: %s" % (template_name, )
    except ImportError:  # 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
    })
Exemplo n.º 49
0
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    template_origin_name = request.GET.get("template_origin", None)
    if template_origin_name is None:
        return HttpResponseBadRequest('"template_origin" key is required')
    try:
        template_origin_name = signing.loads(template_origin_name)
    except Exception:
        return HttpResponseBadRequest('"template_origin" is invalid')
    template_name = request.GET.get("template", template_origin_name)

    final_loaders = []

    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is not None:
            final_loaders.append(loader)

    for loader in final_loaders:
        origin = Origin(template_origin_name)
        try:
            source = loader.get_contents(origin)
            break
        except TemplateDoesNotExist:
            pass
    else:
        source = "Template Does Not Exist: %s" % (template_origin_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

    # Using SimpleTemplateResponse avoids running global context processors.
    return SimpleTemplateResponse(
        "debug_toolbar/panels/template_source.html",
        {"source": source, "template_name": template_name},
    )
Exemplo n.º 50
0
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}
    )
Exemplo n.º 51
0
def get_django_template(name, dirs=None):
    global django_template_source_loaders
    if django_template_source_loaders is None:
        loaders = []
        for loader_name in settings.JINJA2_TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            if loader is not None:
                loaders.append(loader)
        django_template_source_loaders = tuple(loaders)

    for loader in django_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)
Exemplo n.º 52
0
def get_django_template(name, dirs=None):
    global django_template_source_loaders
    if django_template_source_loaders is None:
        loaders = []
        for loader_name in settings.JINJA2_TEMPLATE_LOADERS:
            loader = find_template_loader(loader_name)
            if loader is not None:
                loaders.append(loader)
        django_template_source_loaders = tuple(loaders)
    
    for loader in django_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)
Exemplo n.º 53
0
    def get_django_template(self, name, dirs=None):
        """ load a template using django instead of jinja2.
        """
        if self._django_template_source_loaders is None:
            loaders = []
            for loader_name in settings.JINJA2_TEMPLATE_LOADERS:
                loader = find_template_loader(loader_name)
                if loader is not None:
                    loaders.append(loader)
            self._django_template_source_loaders = tuple(loaders)

        for loader in self._django_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)
Exemplo n.º 54
0
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.HANDLEBARS_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)