Esempio n. 1
0
    def get_template_sources(self, template_name, template_dirs=None):
        """
        Return possible absolute paths to "template_name" in the current theme
        and any themes it inherits from.
        Any paths that don't lie inside one of the template dirs are excluded
        from the result set for security reasons.
        """
        request = get_current_request()
        mobile = (request and request.mobile)

        active_theme = get_active_theme()
        theme = get_theme(active_theme)
        cached_theme, theme_search_info = self.cached_theme_search_info

        # If the theme changed or the user is previewing a different theme,
        # recalculate theme_search_info.
        # Note that this Loader instance may be shared between multiple threads,
        # so you must be careful when reading/writing
        # self.cached_theme_search_info to ensure that writes in one thread
        # cannot cause unexpected behavior in another thread that is
        # reading/writing self.cached_theme_search_info at the same time.
        if cached_theme != theme:
            theme_search_info = []
            for cur_theme in get_theme_search_order(theme):
                if is_builtin_theme(cur_theme) or not settings.USE_S3_THEME:
                    theme_search_info.append(
                        (cur_theme, get_theme_root(cur_theme), False))
                else:
                    theme_search_info.append((cur_theme, cur_theme, True))
            if theme == active_theme:
                self.cached_theme_search_info = (theme, theme_search_info)

        for cur_theme, cur_theme_root, use_s3_theme in theme_search_info:
            for template_path in (['mobile', 'templates']
                                  if mobile else ['templates']):
                if not use_s3_theme:
                    try:
                        template_file = safe_join(cur_theme_root,
                                                  template_path, template_name)
                    except SuspiciousFileOperation:
                        # The joined path was located outside of template_path,
                        # although it might be inside another one, so this isn't
                        # fatal.
                        continue
                else:
                    template_file = os.path.join(cur_theme_root, template_path,
                                                 template_name)
                origin = Origin(name=template_file,
                                template_name=template_name,
                                loader=self)
                origin.theme = cur_theme
                origin.use_s3_theme = use_s3_theme
                yield origin
 def get_template_path(template_dir, template_name, loader=None):
     """Return Origin object with template file path"""
     return Origin(
         name=join(template_dir, template_name),
         template_name=template_name,
         loader=loader,
     )
 def load_template(self, template_name, template_dirs=None):
     warnings.warn(
         'The load_template() method is deprecated. Use get_template() '
         'instead.',
         RemovedInDjango21Warning,
     )
     source, display_name = self.load_template_source(
         template_name,
         template_dirs,
     )
     origin = Origin(
         name=display_name,
         template_name=template_name,
         loader=self,
     )
     try:
         template = Template(source, origin, template_name, self.engine)
     except TemplateDoesNotExist:
         # If compiling the template we found raises TemplateDoesNotExist,
         # back off to returning the source and display name for the
         # template we were asked to load. This allows for correct
         # identification of the actual template that does not exist.
         return source, display_name
     else:
         return template, None
Esempio n. 4
0
    def get_template_sources(self,
                             template_name,
                             template_dirs=None,
                             app_label=None,
                             model_name=None):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set.

        Source: django.template.loaders.filesystem.Loader
        Hard override accepts app_label and model_name
        """
        if not template_dirs:
            template_dirs = self.get_dirs(app_label=app_label,
                                          model_name=model_name)
        for template_dir in template_dirs:
            try:
                name = safe_join(template_dir, template_name)
            except SuspiciousFileOperation:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue

            yield Origin(
                name=name,
                template_name=template_name,
                loader=self,
            )
Esempio n. 5
0
    def render(self, context={}):
        """Render's a template, context can be a Django Context or a
        dictionary.
        """
        # flatten the Django Context into a single dictionary.
        context_dict = {}
        if hasattr(context, 'dicts'):
            for d in context.dicts:
                context_dict.update(d)
        else:
            context_dict = context

            # Django Debug Toolbar needs a RequestContext-like object in order
            # to inspect context.
            class FakeRequestContext:
                dicts = [context]
            context = FakeRequestContext()

        # Used by debug_toolbar.
        if settings.TEMPLATE_DEBUG:
            from django.test import signals
            self.origin = Origin(self.filename)
            signals.template_rendered.send(sender=self, template=self,
                                           context=context)

        # Jinja2 internally converts the context instance to a dictionary, thus
        # we need to store the current_app attribute as a key/value pair.
        context_dict['_current_app'] = getattr(context, 'current_app', None)

        return super(Template, self).render(context_dict)
Esempio n. 6
0
 def find_template(self, name, dirs=None):
     """
     RemovedInDjango21Warning: An internal method to lookup the template
     name in all the configured loaders.
     """
     key = self.cache_key(name, dirs)
     try:
         result = self.find_template_cache[key]
     except KeyError:
         result = None
         for loader in self.loaders:
             try:
                 template, display_name = loader(name, dirs)
             except TemplateDoesNotExist:
                 pass
             else:
                 origin = Origin(
                     name=display_name,
                     template_name=name,
                     loader=loader,
                 )
                 result = template, origin
                 break
     self.find_template_cache[key] = result
     if result:
         return result
     else:
         self.template_cache[key] = TemplateDoesNotExist
         raise TemplateDoesNotExist(name)
Esempio n. 7
0
    def render(self, context={}):
        """Render's a template, context can be a Django Context or a
        dictionary.
        """
        # flatten the Django Context into a single dictionary.
        context_dict = {}
        if hasattr(context, 'dicts'):
            for d in context.dicts:
                context_dict.update(d)
        else:
            context_dict = context

            # Django Debug Toolbar needs a RequestContext-like object in order
            # to inspect context.
            class FakeRequestContext:
                dicts = [context]
            context = FakeRequestContext()

        # Used by debug_toolbar.
        if settings.TEMPLATE_DEBUG:
            from django.test import signals
            self.origin = Origin(self.filename)
            signals.template_rendered.send(sender=self, template=self,
                                           context=context)

        return super(Template, self).render(context_dict)
Esempio n. 8
0
    def _generate_template_source(self, template_name, design):
        """Generate template source."""
        template_source = join(self._app_dir, 'templates', design,
                               template_name)

        if isfile(template_source):
            if VERSION[:2] >= (1, 9):
                template_source = Origin(name=template_source)
            return [template_source]

        return []
Esempio n. 9
0
    def stream(self, context=None):
        if context == None:
            context = {}

        new_ctxt = ctxt_to_dict(context)

        if engines['djinga'].engine.debug:
            # send django signal on template rendering if in debug mode
            from django.test import signals
            from django.template.base import Origin
            self.origin = Origin(self.filename)
            signals.template_rendered.send(sender=self,
                                           template=self,
                                           context=context)

        return super(DjingaTemplate, self).stream(new_ctxt)
Esempio n. 10
0
 def clean(self):
     template = DjangoTemplate('')
     template.source = self.changed_content
     try:
         engine = Engine.get_default()
         lexer = DebugLexer(self.changed_content)
         tokens = lexer.tokenize()
         parser = Parser(tokens, engine.template_libraries,
                         engine.template_builtins, Origin(UNKNOWN_SOURCE))
         parser.parse()
     except TemplateSyntaxError as e:
         exception_info = template.get_exception_info(e, e.token)
         raise ValidationError({
             'changed_content':
             mark_safe(
                 '{message}<br/>Line {line}:\n<pre>{before}<b>{during}</b>{after}</pre>'
                 .format(**exception_info))
         }) from e
Esempio n. 11
0
    def render(self, context=None, request=None):
        context = ctxt_to_dict(context) if context else {}

        engine = engines['djinga'].engine
        if engine.debug:
            # send django signal on template rendering if in debug mode
            from django.test import signals
            from django.template.base import Origin
            self.origin = Origin(self.filename)
            signals.template_rendered.send(sender=self,
                                           template=self,
                                           context=context)

        # adds the context processors (without the builtin ones)
        for cp in engine.template_context_processors:
            context.update(cp(request))

        return super(DjingaTemplate, self).render(context)
Esempio n. 12
0
    def get_template_sources(self, template_name, template_dirs=None):
        "Template loader that loads templates from a ZIP file."

        template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", ['library.zip'])

        try :
            yield self.templates_dict[template_name]._origin
        except KeyError:
            # Try each ZIP file in TEMPLATE_ZIP_FILES.
            for fname in template_zipfiles:
                try:
                    z = zipfile.ZipFile(fname)
                    source = z.read('templates/%s' % (template_name))
                except (IOError, KeyError):
                    continue
                z.close()
                origin = Origin(name=template_name, template_name=template_name, loader=self)
                self.templates_dict[template_name]= EntryLoaderCache(origin=origin, content=source)
                yield origin
Esempio n. 13
0
        def get_contents(self, origin):
            """
            Used by Django 1.9+
            """
            name, _extension = os.path.splitext(origin.name)
            template_name, _extension = os.path.splitext(origin.template_name)

            for extension in HAML_EXTENSIONS:
                try_name = self._generate_template_name(name, extension)
                try_template_name = self._generate_template_name(template_name, extension)
                try_origin = Origin(try_name, try_template_name, origin.loader)
                try:
                    haml_source = super(Loader, self).get_contents(try_origin)
                except TemplateDoesNotExist:
                    pass
                else:
                    haml_parser = Compiler()
                    return haml_parser.process(haml_source)

            raise TemplateDoesNotExist(origin.template_name)
Esempio n. 14
0
 def get_template(self, template_name, *args, **kwargs):
     """
     Return the template with the given name. The template_name should have the type
     (``{html}`` or ``{plaintext}``) appended to the template model instance name.
     """
     # use get_model because models.py imports this module - avoid cyclic imports
     template_model = apps.get_model("impression", "Template")
     match = self.name_pattern.match(template_name)
     if not match:
         raise ValueError(
             'template_name must end with either "{html}" or "{plaintext}"')
     template_shortname = match[1]
     body_type = match[2]
     template = template_model.objects.get(name=template_shortname)
     origin = Origin(
         name="Impression Model Template",
         template_name=template_name,
         loader=type(self).__name__,
     )
     return DjangoTemplate(
         self.get_template_body(template, body_type),
         origin=origin,
     )
Esempio n. 15
0
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if request is not None:

            def _get_val():
                token = get_token(request)
                if token is None:
                    return 'NOTPROVIDED'
                else:
                    return smart_text(token)

            context["request"] = request
            context["csrf_token"] = SimpleLazyObject(_get_val)

            # Support for django context processors
            for processor in self.backend.context_processors:
                context.update(processor(request))

        if settings.TEMPLATE_DEBUG:
            from django.test import signals
            self.template.origin = Origin(self.template.filename)
            context_obj = Context(context)

            context_processors = {}
            if request is not None:
                for processor in self.backend.context_processors:
                    context_processors[processor.__name__] = processor(request)
            context_obj.context_processors = context_processors

            signals.template_rendered.send(sender=self,
                                           template=self.template,
                                           context=context_obj)

        return self.template.render(context)
Esempio n. 16
0
 def get_template_path(template_dir, template_name):
     """Return Origin object with template file path"""
     return Origin(name=join(template_dir, template_name))
def get_template_path(template_dir, template_name, loader=None):
    return Origin(
        name=join(template_dir, template_name),
        template_name=template_name,
        loader=loader,
    )
Esempio n. 18
0
 def get_template_sources(self, template_name):
     yield Origin(
         name=template_name,
         template_name=template_name,
         loader=self,
     )