def load_template(self, template_name, template_dirs=None):
        lang = translation.get_language() or 'en'
        key = '%s-%s' % (lang, template_name)

        if key not in self.template_cache:
            # Path in the cache directory
            output_path = os.path.join(self.__cache_dir, lang, template_name)

            # Load template
            if os.path.exists(output_path):
                # Prefer precompiled version
                template = codecs.open(output_path, 'r', 'utf-8').read()
                origin = StringOrigin(template)
            else:
                template, origin = self.find_template(template_name,
                                                      template_dirs)

                # Compile template (we shouldn't compile anything at runtime.)
                #template, context = compile(template, loader = lambda path: self.find_template(path)[0], path=template_name)

            # Turn into Template object
            template = get_template_from_string(template, origin,
                                                template_name)

            # Save in cache
            self.template_cache[key] = template

        # Return result
        return self.template_cache[key], None
Example #2
0
    def clean_content(self):
        content = self.cleaned_data.get('content', '')
        if content:

            # Pre-Django1.9
            try:
                from django.template.debug import DebugLexer, DebugParser
            # Django1.9
            except ImportError:
                from django.template import Template
                template = Template(template_string=content)
                template.compile_nodelist()
            # Pre-Django1.9
            else:
                origin = StringOrigin(content)
                lexer = DebugLexer(content, origin)
                try:
                    parser = DebugParser(lexer.tokenize())
                    parser.parse()
                except Exception as e:
                    self.exc_info = sys.exc_info()
                    if not hasattr(self.exc_info[1], 'django_template_source'):
                        self.exc_info[1].django_template_source = origin, (0,
                                                                           0)
                    raise forms.ValidationError('Invalid Django Template')
        return content
Example #3
0
    def render(self, context):
        # pagelets can automagically use pagelets templatetags
        # in order to remove boilerplate
        loaded_cms = conf.AUTO_LOAD_TEMPLATE_TAGS + self.content
        """
        skip the first portions of render_to_string() ( finding the template )
         and go directly to compiling the template/pagelet
        render_to_string abbreviated:
                def render_to_string(template_name, dictionary=None, context_instance=None):
                       t = select/get_template(template_name)
                               template = get_template_from_string(source, origin, template_name)
                                       return Template(source, origin, name)
                       t.render(context_instance)

        """
        #XXX is this what the origin should be?
        origin = StringOrigin('pagelet: %s' % self.slug)
        compiled = compile_string(loaded_cms, origin).render(context)
        try:
            if self.type in ('html', 'tinymce', 'wymeditor'):
                html = compiled
            elif self.type == "textile":
                from textile import textile
                html = textile(str(compiled))
            elif self.type == "markdown":
                from markdown import markdown
                html = markdown(compiled)
            return html
        except TemplateSyntaxError as e:
            return 'Syntax error, %s' % e

        raise Exception("Unsupported template content type '%s'" %
                        self.content.content_type)
Example #4
0
    def testViewNonexistentPagelet(self):
        template_str = """{% spaceless %}
{% load pagelet_tags %}
{% render_pagelet 'nonexistent-pagelet' %}
{% endspaceless %}"""
        origin = StringOrigin('test')
        compiled = compile_string(template_str, origin).render(Context())
        self.assertEqual(
            compiled,
            '<div class="pagelet nonexistent-pagelet"><div class="pagelet-content"></div></div>'
        )
Example #5
0
    def _resolve_value(self, context):
        if settings.TEMPLATE_DEBUG:
            from django.template.debug import DebugLexer, DebugParser
            lexer_class, parser_class = DebugLexer, DebugParser
        else:
            lexer_class, parser_class = Lexer, Parser

        lexer = lexer_class(self._logic, StringOrigin(self._logic))
        parser = parser_class(lexer.tokenize())
        parser.tags = self._tag_library
        nodelist = parser.parse()
        return u''.join(node.render(context) for node in nodelist)
Example #6
0
 def clean_content(self):
     content = self.cleaned_data.get('content', '')
     if content:
         origin = StringOrigin(content)
         lexer = DebugLexer(content, origin)
         try:
             parser = DebugParser(lexer.tokenize())
             parser.parse()
         except Exception as e:
             self.exc_info = sys.exc_info()
             if not hasattr(self.exc_info[1], 'django_template_source'):
                 self.exc_info[1].django_template_source = origin, (0, 0)
             raise forms.ValidationError('Invalid Django Template')
     return content
Example #7
0
    def render_template(self, template_string):
        """Used to render an "inner" template, ie one which
        is passed as an argument to spurl"""
        original_autoescape = self.context.autoescape
        self.context.autoescape = False

        template = Template('')
        if TEMPLATE_DEBUG:
            origin = StringOrigin(template_string)
        else:
            origin = None

        template.nodelist = self.compile_string(template_string, origin)

        rendered = template.render(self.context)
        self.context.autoescape = original_autoescape
        return rendered
Example #8
0
    def clean_content(self):
        content = self.cleaned_data.get('content', '')
        if content:
            origin = StringOrigin(content)

            try:
                from django.template.debug import DebugLexer, DebugParser
            except ImportError:
                # django.template.debug doesn't exist in Django >= 1.9, so use
                # Template from django.template instead
                from django.template import Template
                # Try to create a Template
                try:
                    template = Template(template_string=origin)
                # This is an error with creating the template
                except Exception as e:
                    self.exc_info = {
                        'message': e.args,
                        'line': e.token.lineno,
                        'name': origin.name,
                    }
                    raise forms.ValidationError('Invalid Django Template')
                # Template has been created; try to parse
                try:
                    template.compile_nodelist()
                # This is an error with parsing
                except Exception as e:
                    # The data we pass to the views is in e.template_debug
                    e.template_debug = template.get_exception_info(e, e.token)
                    self.exc_info = e.template_debug
                    raise forms.ValidationError('Parsing Error')
            else:
                lexer = DebugLexer(content, origin)
                try:
                    parser = DebugParser(lexer.tokenize())
                    parser.parse()
                except Exception as e:
                    self.exc_info = sys.exc_info()
                    if not hasattr(self.exc_info[1], 'django_template_source'):
                        self.exc_info[1].django_template_source = origin, (0, 0)
                    raise forms.ValidationError('Invalid Django Template')
        return content
Example #9
0
    def render_template(self, template_string):
        """Used to render an "inner" template, ie one which
        is passed as an argument to spurl"""
        original_autoescape = self.context.autoescape
        self.context.autoescape = False

        template = Template('')
        template_debug = getattr(
            settings, 'TEMPLATE_DEBUG',
            template.engine.debug if hasattr(template, 'engine') else False)
        if template_debug is True:
            origin = StringOrigin(template_string)
        else:
            origin = None

        template.nodelist = self.compile_string(template_string, origin,
                                                template_debug)

        rendered = template.render(self.context)
        self.context.autoescape = original_autoescape
        return rendered
Example #10
0
 def compile_string(self, url, template_str):
     origin = StringOrigin(url)
     return compile_string(template_str, origin).render(Context())