Python jinja2.exceptions.TemplateError() Examples

The following are 13 code examples of jinja2.exceptions.TemplateError(). 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.exceptions , or try the search function .
Example #1
Source File: regen_docs.py    From mkdocstrings with ISC License 6 votes vote down vote up
def main():
    """Regenerate pages listed in global `REGEN` list."""
    env = SandboxedEnvironment(undefined=StrictUndefined)
    for target, get_data, template in REGEN:
        print("Regenerating", target)
        data = get_data()
        template_text = requests.get(template).text
        try:
            rendered = env.from_string(template_text).render(**data)
        except TemplateError as error:
            print("Error while regenerating", target)
            print(error)
            return 1
        with open(target, "w") as target:
            target.write(rendered)
    return 0 
Example #2
Source File: regen_docs.py    From aria2p with ISC License 6 votes vote down vote up
def main():
    """Regenerate pages listed in global `REGEN` list."""
    env = SandboxedEnvironment(undefined=StrictUndefined)
    for target, get_data, template in REGEN:
        print("Regenerating", target)
        data = get_data()
        if Path(template).exists():
            with open(template) as fd:
                template_text = fd.read()
        else:
            template_text = requests.get(template).text
        try:
            rendered = env.from_string(template_text).render(**data)
        except TemplateError as error:
            print("Error while regenerating", target)
            print(error)
            return 1
        with open(target, "w") as target:
            target.write(rendered)
    return 0 
Example #3
Source File: __init__.py    From python-docx-template with GNU Lesser General Public License v2.1 6 votes vote down vote up
def render_xml(self, src_xml, context, jinja_env=None):
        src_xml = src_xml.replace(r'<w:p>', '\n<w:p>')
        try:
            if jinja_env:
                template = jinja_env.from_string(src_xml)
            else:
                template = Template(src_xml)
            dst_xml = template.render(context)
        except TemplateError as exc:
            if hasattr(exc, 'lineno') and exc.lineno is not None:
                line_number = max(exc.lineno - 4, 0)
                exc.docx_context = map(lambda x: re.sub(r'<[^>]+>', '', x),
                                       src_xml.splitlines()[line_number:(line_number + 7)])
            raise exc
        dst_xml = dst_xml.replace('\n<w:p>', '<w:p>')
        dst_xml = (dst_xml
                   .replace('{_{', '{{')
                   .replace('}_}', '}}')
                   .replace('{_%', '{%')
                   .replace('%_}', '%}'))
        return dst_xml 
Example #4
Source File: test_mails.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def test_invalid_block_templated_message_templates(app_with_mail):
    """Test invalid templates."""
    with app_with_mail.app_context():
        with pytest.raises(TemplateError) as ex:
            BlockTemplatedMessage("mail/blank.html")
        assert "No block with name 'subject'" in str(ex.value)

        with pytest.raises(TemplateError) as ex:
            BlockTemplatedMessage("mail/subject_only.html")
        assert "No block with name 'body_plain'" in str(ex.value) 
Example #5
Source File: messages.py    From invenio-app-ils with MIT License 5 votes vote down vote up
def render_block(self, template, block_name):
        """Return a Jinja2 block as a string."""
        new_context = template.new_context
        if block_name not in template.blocks:
            raise TemplateError("No block with name '{}'".format(block_name))
        lines = template.blocks[block_name](new_context(vars=self.ctx))
        return "".join(lines) 
Example #6
Source File: models.py    From linkedevents with MIT License 5 votes vote down vote up
def render(self, context, language_code=DEFAULT_LANG):
        """
        Render this notification template with given context and language

        Returns a dict containing all content fields of the template. Example:

        {'subject': 'bar', 'body': 'baz', 'html_body': '<b>foobar</b>'}

        """

        env = SandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined)
        env.filters['format_datetime'] = format_datetime

        logger.debug('Rendering template for notification %s' % self.type)

        activate(language_code)

        try:
            rendered_notification = {
                attr: env.from_string(getattr(self, attr)).render(context)
                for attr in ('subject', 'html_body')
            }
            if self.body:
                rendered_notification['body'] = env.from_string(self.body).render(context)
            else:
                # if text body is empty use html body without tags as text body
                rendered_notification['body'] = strip_tags(rendered_notification['html_body'])
            return rendered_notification
        except TemplateError as e:
            raise NotificationTemplateException(e) from e 
Example #7
Source File: parser.py    From jinja2-live-parser with MIT License 5 votes vote down vote up
def convert():
    jinja2_env = Environment()

    # Load custom filters
    custom_filters = get_custom_filters()
    app.logger.debug('Add the following customer filters to Jinja environment: %s' % ', '.join(custom_filters.keys()))
    jinja2_env.filters.update(custom_filters)

    # Load the template
    try:
        jinja2_tpl = jinja2_env.from_string(request.form['template'])
    except (exceptions.TemplateSyntaxError, exceptions.TemplateError) as e:
        return "Syntax error in jinja2 template: {0}".format(e)


    dummy_values = [ 'Lorem', 'Ipsum', 'Amet', 'Elit', 'Expositum',
        'Dissimile', 'Superiori', 'Laboro', 'Torquate', 'sunt',
    ]
    values = {}
    if bool(int(request.form['dummyvalues'])):
        # List template variables (introspection)
        vars_to_fill = meta.find_undeclared_variables(jinja2_env.parse(request.form['template']))

        for v in vars_to_fill:
            values[v] = choice(dummy_values)
    else:
        # Check JSON for errors
        if request.form['input_type'] == "json":
            try:
                values = json.loads(request.form['values'])
            except ValueError as e:
                return "Value error in JSON: {0}".format(e)
        # Check YAML for errors
        elif request.form['input_type'] == "yaml":
            try:
                values = yaml.load(request.form['values'])
            except (ValueError, yaml.parser.ParserError, TypeError) as e:
                return "Value error in YAML: {0}".format(e)
        else:
            return "Undefined input_type: {0}".format(request.form['input_type'])

    # If ve have empty var array or other errors we need to catch it and show
    try:
        rendered_jinja2_tpl = jinja2_tpl.render(values)
    except (exceptions.TemplateRuntimeError, ValueError, TypeError) as e:
        return "Error in your values input filed: {0}".format(e)

    if bool(int(request.form['showwhitespaces'])):
        # Replace whitespaces with a visible character (will be grayed with javascript)
        rendered_jinja2_tpl = rendered_jinja2_tpl.replace(' ', u'•')

    return escape(rendered_jinja2_tpl).replace('\n', '<br />') 
Example #8
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def process_cmds(cmds, overrides):
    """

    :param cmds:
    :param overrides:
    :return:
    """
    data = ''
    for cmd in cmds:
        if cmd.startswith('#'):
            continue
        else:
            try:
                newcmd = Environment(undefined=undefined).from_string(cmd).render(overrides)
                data += "- %s\n" % newcmd.replace(": ", "':' ")
            except TemplateError as e:
                pprint("Error rendering cmd %s. Got: %s" % (cmd, e.message), color='red')
                os._exit(1)
    return data 
Example #9
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def process_ignition_cmds(cmds, overrides):
    """

    :param cmds:
    :param overrides:
    :return:
    """
    path = '/usr/local/bin/first.sh'
    permissions = '700'
    content = ''
    for cmd in cmds:
        try:
            newcmd = Environment(undefined=undefined).from_string(cmd).render(overrides)
            content += "%s\n" % newcmd
        except TemplateError as e:
            pprint("Error rendering cmd %s. Got: %s" % (cmd, e.message), color='red')
            os._exit(1)
    if content == '':
        return content
    else:
        if not content.startswith('#!'):
            content = "#!/bin/sh\n%s" % content
        content = quote(content)
        data = {'filesystem': 'root', 'path': path, 'mode': int(permissions, 8),
                "contents": {"source": "data:,%s" % content, "verification": {}}}
        return data 
Example #10
Source File: validators.py    From intake with MIT License 5 votes vote down vote up
def check_compilation(self, data):
        """Tests that a template string can be successfully compiled
        """
        exception = None
        result = None
        try:
            result = utils.compile_template_string(data)
        except TemplateError as error:
            exception = error
        return result, exception 
Example #11
Source File: template_renderer.py    From hokusai with MIT License 5 votes vote down vote up
def render(self):
    try:
      return self.load_template().render(**self.template_config)
    except TemplateError, e:
      raise HokusaiError("Rendering template raised error %s <message '%s'>" % (e.__class__, e.message)) 
Example #12
Source File: messages.py    From invenio-app-ils with MIT License 4 votes vote down vote up
def __init__(self, template, ctx={}, **kwargs):
        """Build message body and HTML based on the provided template.

        The template needs to provide two blocks: subject and body. An optional
        html block can also be provided for HTML rendered emails.

        :param template: Path to the template file.
        :param ctx: A mapping containing additional information passed to the
            template.
        :param **kwargs: Named arguments as defined in
            :class:`flask_mail.Message`.
        """
        self.template = template
        self.id = str(uuid.uuid4())

        ctx.update(dict(
            spa_routes=dict(
                HOST=current_app.config["SPA_HOST"],
                PATHS=current_app.config["SPA_PATHS"],
            ),
        ))
        self.ctx = ctx

        tmpl = current_app.jinja_env.get_template(template)
        kwargs["subject"] = self.render_block(tmpl, "subject").strip()
        kwargs["body"] = self.render_block(tmpl, "body_plain")
        try:
            kwargs["html"] = self.render_block(tmpl, "body_html")
        except TemplateError:
            kwargs["html"] = kwargs["body"]

        footer_tmpl = current_app.jinja_env.get_template(self.FOOTER_TEMPLATE)
        footer_plain = self.render_block(footer_tmpl, "footer_plain")
        try:
            footer_html = self.render_block(footer_tmpl, "footer_html")
        except TemplateError:
            footer_html = footer_plain

        kwargs["body"] += footer_plain
        kwargs["html"] += footer_html

        kwargs["body"] = kwargs["body"].strip()
        kwargs["html"] = kwargs["html"].strip()

        kwargs.setdefault("sender", current_app.config["MAIL_NOTIFY_SENDER"])
        kwargs.setdefault("cc", current_app.config["MAIL_NOTIFY_CC"])
        kwargs.setdefault("bcc", current_app.config["MAIL_NOTIFY_BCC"])

        super(BlockTemplatedMessage, self).__init__(**kwargs) 
Example #13
Source File: code_generator_online.py    From pytgbot with GNU General Public License v3.0 4 votes vote down vote up
def output(folder, results, html_content=None):
    can_quit = False
    do_overwrite = confirm("Can the folder {path} be overwritten?".format(path=folder))
    print("vvvvvvvvv")
    while not can_quit:
        if do_overwrite:
            try:
                import Send2Trash
                Send2Trash.send2trash(folder)
            except ImportError:
                import shutil
                shutil.rmtree(folder)
            # end try
        # end if

        # write crawled data
        mkdir_p(folder)
        with open(path_join(folder, "api.py"), "w") as f:
            f.write("[\n    ")
            f.write(",\n    ".join([repr(result) for result in results]))
            f.write("\n]")
            # end for
        # end with
        if html_content:
            with open(path_join(folder, "api.html"), "wb") as f:
                f.write(html_content)
            # end with
        # end if

        # write templates
        try:
            safe_to_file(folder, results)
        except TemplateError as e:
            if isinstance(e, TemplateSyntaxError):
                logger.exception("Template error at {file}:{line}".format(file=e.filename, line=e.lineno))
            else:
                logger.exception("Template error.")
                # end if
        # end try
        print("Writen to file.")
        can_quit = not confirm("Write again after reloading templates?", default=True)
    print("#########")
    print("Exit.")
# end def