Python jinja2.TemplateSyntaxError() Examples

The following are 27 code examples of jinja2.TemplateSyntaxError(). 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 jinja2 , or try the search function .
Example #1
Source File: templating.py    From statik with MIT License 6 votes vote down vote up
def template_exception_handler(fn, error_context, filename=None):
    """Calls the given function, attempting to catch any template-related errors, and
    converts the error to a Statik TemplateError instance. Returns the result returned
    by the function itself."""
    error_message = None
    if filename:
        error_context.update(filename=filename)
    try:
        return fn()
    except jinja2.TemplateSyntaxError as exc:
        error_context.update(filename=exc.filename, line_no=exc.lineno)
        error_message = exc.message
    except jinja2.TemplateError as exc:
        error_message = exc.message
    except Exception as exc:
        error_message = "%s" % exc

    raise TemplateError(message=error_message, context=error_context) 
Example #2
Source File: jinja_helpers.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def render(self, *args, **kwargs):
        """Render the Jinja2 template with the provided context.

        All arguments are passed through; this just wraps the Jinja2 template render method
        to handle syntax error exceptions so that Jinja2 does not need to be imported anywhere
        but this file.
        """
        _add_to_path()
        from jinja2 import TemplateSyntaxError

        try:
            return self.template.render(*args, **kwargs)
        except TemplateSyntaxError as e:
            print(
                "Jinja2 template syntax error during render: {}:{} error: {}".
                format(e.filename, e.lineno, e.message))
            raise e 
Example #3
Source File: request_handler.py    From zoe with Apache License 2.0 5 votes vote down vote up
def render(self, template_name, **kwargs):
        """ renders a template file. """
        template = self._jinja_env.get_template(template_name)
        try:
            html = self._render(template, **kwargs)
        except TemplateSyntaxError as e:
            self.error_page('Template syntax error at {}:{}:<br> {}'.format(e.name, e.lineno, e.message), 500)
            return
        except Exception as e:
            log.exception('Jinja2 exception while rendering the template {}'.format(template_name))
            self.error_page('Jinja2 template exception: {}'.format(e), 500)
            return
        self.finish(html) 
Example #4
Source File: debug.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_regular_syntax_error(self):
        def test():
            raise TemplateSyntaxError('wtf', 42)
        self.assert_traceback_matches(test, r'''
  File ".*debug.pyc?", line \d+, in test
    raise TemplateSyntaxError\('wtf', 42\)
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
  line 42''') 
Example #5
Source File: debug.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_syntax_error(self):
        # XXX: the .*? is necessary for python3 which does not hide
        # some of the stack frames we don't want to show.  Not sure
        # what's up with that, but that is not that critical.  Should
        # be fixed though.
        self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)
  File ".*?syntaxerror.html", line 4, in (template|<module>)
    \{% endif %\}.*?
(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
    ''') 
Example #6
Source File: debug.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_regular_syntax_error(self):
        def test():
            raise TemplateSyntaxError('wtf', 42)
        self.assert_traceback_matches(test, r'''
  File ".*debug.pyc?", line \d+, in test
    raise TemplateSyntaxError\('wtf', 42\)
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
  line 42''') 
Example #7
Source File: debug.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_syntax_error(self):
        # XXX: the .*? is necessary for python3 which does not hide
        # some of the stack frames we don't want to show.  Not sure
        # what's up with that, but that is not that critical.  Should
        # be fixed though.
        self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)
  File ".*?syntaxerror.html", line 4, in (template|<module>)
    \{% endif %\}.*?
(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
    ''') 
Example #8
Source File: pdfjinja.py    From pdfjinja with MIT License 5 votes vote down vote up
def parse_annotations(self, pgnum, page):
        annots = page.annots
        if isinstance(page.annots, PDFObjRef):
            annots = page.annots.resolve()

        annots = (
            r.resolve() for r in annots if isinstance(r, PDFObjRef))

        widgets = (
            r for r in annots if r["Subtype"].name == "Widget")

        for ref in widgets:
            data_holder = ref
            try:
                name = ref["T"]
            except KeyError:
                ref = ref['Parent'].resolve()
                name = ref['T']
            field = self.fields.setdefault(name, {"name": name, "page": pgnum})
            allowed_fts = ("Btn", "Tx", "Ch", "Sig")
            if "FT" in data_holder and data_holder["FT"].name in allowed_fts:
                field["rect"] = data_holder["Rect"]

            if "TU" in ref:
                tmpl = ref["TU"]

                try:
                    if ref["TU"].startswith(b"\xfe"):
                        tmpl = tmpl.decode("utf-16")
                    else:
                        tmpl = tmpl.decode("utf-8")
                    field["template"] = self.jinja_env.from_string(tmpl)
                except (UnicodeDecodeError, TemplateSyntaxError) as err:
                    logger.error("%s: %s %s", name, tmpl, err) 
Example #9
Source File: module_logic.py    From govready-q with GNU General Public License v3.0 5 votes vote down vote up
def get_jinja2_template_vars(template):
    from jinja2 import meta, TemplateSyntaxError
    env = SandboxedEnvironment()
    try:
        expr = env.parse(template)
    except TemplateSyntaxError as e:
        raise Exception("expression {} is invalid: {}".format(template, e))
    return set(meta.find_undeclared_variables(expr)) 
Example #10
Source File: jinja2.py    From python2017 with MIT License 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name), self)
        except jinja2.TemplateNotFound as exc:
            six.reraise(
                TemplateDoesNotExist,
                TemplateDoesNotExist(exc.name, backend=self),
                sys.exc_info()[2],
            )
        except jinja2.TemplateSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            six.reraise(TemplateSyntaxError, new, sys.exc_info()[2]) 
Example #11
Source File: jinja2.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name))
        except jinja2.TemplateNotFound as exc:
            six.reraise(
                TemplateDoesNotExist,
                TemplateDoesNotExist(exc.name, backend=self),
                sys.exc_info()[2],
            )
        except jinja2.TemplateSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            six.reraise(TemplateSyntaxError, new, sys.exc_info()[2]) 
Example #12
Source File: debug.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_regular_syntax_error(self):
        def test():
            raise TemplateSyntaxError('wtf', 42)
        self.assert_traceback_matches(test, r'''
  File ".*debug.pyc?", line \d+, in test
    raise TemplateSyntaxError\('wtf', 42\)
(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
  line 42''') 
Example #13
Source File: debug.py    From Flask-P2P with MIT License 5 votes vote down vote up
def test_syntax_error(self):
        # XXX: the .*? is necessary for python3 which does not hide
        # some of the stack frames we don't want to show.  Not sure
        # what's up with that, but that is not that critical.  Should
        # be fixed though.
        self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)
  File ".*?syntaxerror.html", line 4, in (template|<module>)
    \{% endif %\}.*?
(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
    ''') 
Example #14
Source File: jinja2.py    From python with Apache License 2.0 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name), self)
        except jinja2.TemplateNotFound as exc:
            six.reraise(
                TemplateDoesNotExist,
                TemplateDoesNotExist(exc.name, backend=self),
                sys.exc_info()[2],
            )
        except jinja2.TemplateSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            six.reraise(TemplateSyntaxError, new, sys.exc_info()[2]) 
Example #15
Source File: jinja2.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name))
        except jinja2.TemplateNotFound as exc:
            six.reraise(TemplateDoesNotExist, TemplateDoesNotExist(exc.args),
                        sys.exc_info()[2])
        except jinja2.TemplateSyntaxError as exc:
            six.reraise(TemplateSyntaxError, TemplateSyntaxError(exc.args),
                        sys.exc_info()[2]) 
Example #16
Source File: jinja2.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name), self)
        except jinja2.TemplateNotFound as exc:
            raise TemplateDoesNotExist(exc.name, backend=self) from exc
        except jinja2.TemplateSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            raise new from exc 
Example #17
Source File: render_test.py    From rdm with MIT License 5 votes vote down vote up
def test_undefined(self):
        with raises(TemplateSyntaxError):
            input_string = "{% huhwhat 'hotel', 'california' %}"
            self.render_from_string(input_string, context={}) 
Example #18
Source File: jinja_helpers.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def __init__(self, env, fn):
        """Load and parse a Jinja2 template given a Jinja2 environment and the template file name.

        Create the environment using make_jinja_environment().

        Syntax errors are caught, have their details printed, then are re-raised (to stop execution).
        """
        _add_to_path()
        from jinja2 import TemplateSyntaxError
        try:
            self.template = env.get_template(fn)
        except TemplateSyntaxError as e:
            print("Jinja2 template syntax error during parse: {}:{} error: {}".
                  format(e.filename, e.lineno, e.message))
            raise e 
Example #19
Source File: _extensions.py    From assembly with MIT License 5 votes vote down vote up
def fail(self, message):
        raise TemplateSyntaxError(message, self.token.lineno, self.stream.name,
                                  self.stream.filename) 
Example #20
Source File: jinja2.py    From bioforum with MIT License 5 votes vote down vote up
def get_template(self, template_name):
        try:
            return Template(self.env.get_template(template_name), self)
        except jinja2.TemplateNotFound as exc:
            raise TemplateDoesNotExist(exc.name, backend=self) from exc
        except jinja2.TemplateSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            raise new from exc 
Example #21
Source File: tests.py    From jinja2-django-tags with MIT License 5 votes vote down vote up
def test_errors(self):
        template = "{% url 'my_view' kw1='foo' 123 %}"
        msg = "got 'integer', expected name for keyword argument"

        with self.assertRaisesMessage(TemplateSyntaxError, msg):
            self.env.from_string(template) 
Example #22
Source File: tests.py    From jinja2-django-tags with MIT License 5 votes vote down vote up
def test_errors(self):
        template1 = "{% blocktrans %}foo{% plural %}bar{% endblocktrans %}"
        template2 = "{% blocktrans count counter=10 %}foo{% endblocktrans %}"

        error_messages = [
            (template1, 'used plural without specifying count'),
            (template2, 'plural form not found'),
        ]

        for template, msg in error_messages:
            with self.assertRaisesMessage(TemplateSyntaxError, msg):
                self.env.from_string(template) 
Example #23
Source File: tests.py    From jinja2-django-tags with MIT License 5 votes vote down vote up
def test_errors(self):
        template1 = "{% trans 'Hello World' foo %}"
        template2 = "{% trans 'Hello World' noop context 'some context' %}"
        template3 = "{% trans 'Hello World' context 'some context' noop %}"

        error_messages = [
            (template1, "expected 'noop', 'context' or 'as'"),
            (template2, "noop translation can't have context"),
            (template3, "noop translation can't have context"),
        ]

        for template, msg in error_messages:
            with self.assertRaisesMessage(TemplateSyntaxError, msg):
                self.env.from_string(template) 
Example #24
Source File: models.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def render(self, variables):
        """
        Render the template using Jinja2.
        """
        environment = Environment()

        def prefix_list(asn, address_family=0):
            """
            Return the prefixes for the given AS.
            """
            if not asn:
                return []
            autonomous_system = AutonomousSystem.objects.get(asn=asn)
            return autonomous_system.get_irr_as_set_prefixes(address_family)

        def cisco_password(password):
            from utils.crypto.cisco import MAGIC as CISCO_MAGIC

            if password.startswith(CISCO_MAGIC):
                return password[2:]
            return password

        # Add custom filters to our environment
        environment.filters["prefix_list"] = prefix_list
        environment.filters["cisco_password"] = cisco_password

        # Try rendering the template, return a message about syntax issues if there
        # are any
        try:
            jinja2_template = environment.from_string(self.template)
            return jinja2_template.render(variables)
        except TemplateSyntaxError as e:
            return f"Syntax error in template at line {e.lineno}: {e.message}"
        except Exception as e:
            return str(e) 
Example #25
Source File: util.py    From pyinfra with MIT License 5 votes vote down vote up
def get_arg_value(state, host, arg):
    '''
    Runs string arguments through the jinja2 templating system with a state and
    host. Used to avoid string formatting in deploy operations which result in
    one operation per host/variable. By parsing the commands after we generate
    the ``op_hash``, multiple command variations can fall under one op.
    '''

    if isinstance(arg, six.string_types):
        data = {
            'host': host,
            'inventory': state.inventory,
        }

        try:
            return get_template(arg, is_string=True).render(data)
        except (TemplateSyntaxError, UndefinedError) as e:
            raise PyinfraError('Error in template string: {0}'.format(e))

    elif isinstance(arg, list):
        return [get_arg_value(state, host, value) for value in arg]

    elif isinstance(arg, tuple):
        return tuple(get_arg_value(state, host, value) for value in arg)

    elif isinstance(arg, dict):
        return {
            key: get_arg_value(state, host, value)
            for key, value in six.iteritems(arg)
        }

    return arg 
Example #26
Source File: mail.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_html_file(self):
		"""
		Load the configured HTML file into the WebKit engine so the contents can
		be previewed.
		"""
		html_file = self.config.get('mailer.html_file')
		if not (html_file and os.path.isfile(html_file) and os.access(html_file, os.R_OK)):
			return

		try:
			with codecs.open(html_file, 'r', encoding='utf-8') as file_h:
				html_data = file_h.read()
		except UnicodeDecodeError:
			self.info_bar_label.set_text("Source file is not UTF-8 encoded.")
			return

		try:
			html_data = mailer.render_message_template(html_data, self.config)
		except jinja2.TemplateSyntaxError as error:
			self.info_bar_label.set_text("Template syntax error: {error.message} on line {error.lineno}.".format(error=error))
			self.info_bar.show()
		except jinja2.UndefinedError as error:
			self.info_bar_label.set_text("Template undefined error: {error.message}.".format(error=error))
			self.info_bar.show()
		except TypeError as error:
			self.info_bar_label.set_text("Template type error: {0}.".format(error.args[0]))
			self.info_bar.show()
		else:
			html_file_uri = urllib.parse.urlparse(html_file, 'file').geturl()
			self.webview.load_html_data(html_data, html_file_uri)
			self.info_bar.hide() 
Example #27
Source File: module_logic.py    From govready-q with GNU General Public License v3.0 4 votes vote down vote up
def run_impute_conditions(conditions, context):
    # Check if any of the impute conditions are met based on
    # the questions that have been answered so far and return
    # the imputed value. Be careful about values like 0 that
    # are false-y --- must check for "is None" to know if
    # something was imputed or not.
    env = Jinja2Environment()
    for rule in conditions:
        if "condition" in rule:
            condition_func = compile_jinja2_expression(rule["condition"])
            try:
                value = condition_func(context)
            except:
                value = None
        else:
            value = True

        if value:
            # The condition is met. Compute the imputed value.
            if rule.get("value-mode", "raw") == "raw":
                # Imputed value is the raw YAML value.
                value = rule["value"]
            elif rule.get("value-mode", "raw") == "expression":
                value = compile_jinja2_expression(rule["value"])(context)
                if isinstance(value, RenderedAnswer):
                    # Unwrap.
                    value =  value.answer
                elif hasattr(value, "__html__"):
                    # some things might return something that safely wraps a string,
                    # like our SafeString instance
                    value = value.__html__()
                elif hasattr(value, "as_raw_value"):
                    # RenderedProject, RenderedOrganization
                    value = value.as_raw_value()
            elif rule.get("value-mode", "raw") == "template":
                env = Jinja2Environment(autoescape=True)
                try:
                    template = env.from_string(rule["value"])
                except jinja2.TemplateSyntaxError as e:
                    raise ValueError("There was an error loading the template %s: %s" % (rule["value"], str(e)))
                value = template.render(context)
            else:
                raise ValueError("Invalid impute condition value-mode.")

            # Since the imputed value may be None, return
            # the whole thing in a tuple to distinguish from
            # a None indicating the lack of an imputed value.
            return (value,)
    return None