Python jinja2.TemplateError() Examples

The following are code examples for showing how to use jinja2.TemplateError(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: qface   Author: Pelagicore   File: generator.py    (license) View Source Project 7 votes vote down vote up
def write(self, file_path: Path, template: str, context: dict={}, preserve: bool = False):
        """Using a template file name it renders a template
           into a file given a context
        """
        if not context:
            context = self.context
        error = False
        try:
            self._write(file_path, template, context, preserve)
        except TemplateSyntaxError as exc:
            message = '{0}:{1} error: {2}'.format(exc.filename, exc.lineno, exc.message)
            click.secho(message, fg='red')
            error = True
        except TemplateNotFound as exc:
            message = '{0} error: Template not found'.format(exc.name)
            click.secho(message, fg='red')
            error = True
        except TemplateError as exc:
            message = 'error: {0}'.format(exc.message)
            click.secho(message, fg='red')
            error = True
        if error and Generator.strict:
            sys.exit(-1) 
Example 2
Project: ivy   Author: dmulholland   File: ivy_jinja.py    (license) View Source Project 6 votes vote down vote up
def callback(page, filename):
        try:
            template = env.get_template(filename)
            return template.render(page)
        except jinja2.TemplateError as err:
            msg =  "------------------------\n"
            msg += "  Jinja Template Error  \n"
            msg += "------------------------\n\n"
            msg += "  Template: %s\n" % filename
            msg += "  Page: %s\n\n" % page['filepath']
            msg += "  %s: %s" % (err.__class__.__name__, err)
            if err.__context__:
                cause = err.__context__
                msg += "\n\n  The following cause was reported:\n\n"
                msg += "  %s: %s" % (cause.__class__.__name__, cause)
            sys.exit(msg) 
Example 3
Project: homeassistant   Author: NAStools   File: template.py    (license) View Source Project 6 votes vote down vote up
def async_render_with_possible_json_value(self, value,
                                              error_value=_SENTINEL):
        """Render template with value exposed.

        If valid JSON will expose value_json too.

        This method must be run in the event loop.
        """
        self._ensure_compiled()

        variables = {
            'value': value
        }
        try:
            variables['value_json'] = json.loads(value)
        except ValueError:
            pass

        try:
            return self._compiled.render(variables).strip()
        except jinja2.TemplateError as ex:
            _LOGGER.error('Error parsing value: %s (value: %s, template: %s)',
                          ex, value, self.template)
            return value if error_value is _SENTINEL else error_value 
Example 4
Project: flasky   Author: RoseOu   File: inheritance.py    (license) View Source Project 5 votes vote down vote up
def test_double_extends(self):
        """Ensures that a template with more than 1 {% extends ... %} usage
        raises a ``TemplateError``.
        """
        try:
            tmpl = env.get_template('doublee')
        except Exception as e:
            assert isinstance(e, TemplateError) 
Example 5
Project: oa_qian   Author: sunqb   File: inheritance.py    (license) View Source Project 5 votes vote down vote up
def test_double_extends(self):
        """Ensures that a template with more than 1 {% extends ... %} usage
        raises a ``TemplateError``.
        """
        try:
            tmpl = env.get_template('doublee')
        except Exception as e:
            assert isinstance(e, TemplateError) 
Example 6
Project: pyetje   Author: rorlika   File: inheritance.py    (license) View Source Project 5 votes vote down vote up
def test_double_extends(self):
        """Ensures that a template with more than 1 {% extends ... %} usage
        raises a ``TemplateError``.
        """
        try:
            tmpl = env.get_template('doublee')
        except Exception as e:
            assert isinstance(e, TemplateError) 
Example 7
Project: constructor   Author: conda   File: jinja.py    (license) View Source Project 5 votes vote down vote up
def render_jinja(data, directory, content_filter):
    loader = FilteredLoader(FileSystemLoader(directory), content_filter)
    env = Environment(loader=loader)
    try:
        template = env.from_string(data)
        rendered = template.render()
    except TemplateError as ex:
        raise UnableToParse(original=ex)
    return rendered 
Example 8
Project: NetOpsWorkshop   Author: ipspace   File: list.py    (license) View Source Project 5 votes vote down vote up
def list_append(self,l,*argv):
    if type(l) is not list:
      raise TemplateError("First argument of append filter must be a list")

    for element in argv:
      if type(element) is list:
        l.extend(element)
      else:
        l.append(element)
    return l 
Example 9
Project: NetOpsWorkshop   Author: ipspace   File: list.py    (license) View Source Project 5 votes vote down vote up
def dict_to_list(self,o):
    if type(o) is not dict:
      raise TemplateError("dict_to_list can only be used on dictionaries")

    l = []
    for k,v in o.items():
      v['id'] = k
      l.append(v)

    return l 
Example 10
Project: NetOpsWorkshop   Author: ipspace   File: net_helper.py    (license) View Source Project 5 votes vote down vote up
def device_type(self,show_ver,*deftype):
    if "Cisco IOS" in show_ver: return "ios"
    if "NX-OS" in show_ver:     return "nx-os"
    if len(deftype) > 0:        return deftype[0]

    raise TemplateError("Unknown device type - did you pass me show version?") 
Example 11
Project: NetOpsWorkshop   Author: ipspace   File: list.py    (license) View Source Project 5 votes vote down vote up
def list_append(self,l,*argv):
    if type(l) is not list:
      raise TemplateError("First argument of append filter must be a list")

    for element in argv:
      if type(element) is list:
        l.extend(element)
      else:
        l.append(element)
    return l 
Example 12
Project: Callandtext   Author: iaora   File: inheritance.py    (license) View Source Project 5 votes vote down vote up
def test_double_extends(self):
        """Ensures that a template with more than 1 {% extends ... %} usage
        raises a ``TemplateError``.
        """
        try:
            tmpl = env.get_template('doublee')
        except Exception as e:
            assert isinstance(e, TemplateError) 
Example 13
Project: My-Web-Server-Framework-With-Python2.7   Author: syjsu   File: inheritance.py    (license) View Source Project 5 votes vote down vote up
def test_double_extends(self):
        """Ensures that a template with more than 1 {% extends ... %} usage
        raises a ``TemplateError``.
        """
        try:
            tmpl = env.get_template('doublee')
        except Exception as e:
            assert isinstance(e, TemplateError) 
Example 14
Project: jupyterlab_launcher   Author: jupyterlab   File: handlers.py    (license) View Source Project 5 votes vote down vote up
def render_template(self, name, **ns):
        try:
            return IPythonHandler.render_template(self, name, **ns)
        except TemplateError:
            return DEFAULT_TEMPLATE.generate(
                name=name, path=self.lab_config.templates_dir
            ) 
Example 15
Project: mistral-lint   Author: d0ugal   File: linters.py    (license) View Source Project 5 votes vote down vote up
def _validate_jinja2(template, string, path):
    try:
        env = jinja2.Environment()
        env.parse(string)
    except jinja2.TemplateError:
        lineno = _find_line(template, string)
        return ("E104: Failed to parse jinja2 expression '{}' on line {} in {}"
                .format(template, lineno, path)) 
Example 16
Project: kibitzr   Author: kibitzr   File: jinja_transform.py    (license) View Source Project 5 votes vote down vote up
def render(self, content, context=None):
        from jinja2 import TemplateError
        try:
            return True, self.template.render(context or self.context(content))
        except TemplateError:
            logger.warning("Jinja render failed", exc_info=True)
            return False, None 
Example 17
Project: feedstockrot   Author: axiom-data-science   File: condaforge.py    (license) View Source Project 5 votes vote down vote up
def _get_recipe(self) -> Dict:
        resp = requests.get(self._DEFAULT_RECIPE_URL.format(self.name))
        if resp.status_code != 200:
            return None

        # conda-forge recipes commonly use jinja2 for variables
        try:
            parsed = jinja2.Template(resp.text, undefined=Jinja2NullUndefined)
            rendered = parsed.render()
            return yaml.load(rendered)
        except (jinja2.TemplateError, yaml.YAMLError):
            return None 
Example 18
Project: aiohttp-devtools   Author: aio-libs   File: main.py    (license) View Source Project 5 votes vote down vote up
def generate_file(self, p: Path):
        try:
            template = Template(p.read_text())
            text = template.render(**self.ctx)
        except TemplateError as e:
            raise TemplateError('error in {}'.format(p)) from e
        text = text.strip('\n\t ')
        new_path = self.project_root / p.relative_to(self.template_dir)
        if len(text) < 3:
            # empty files don't get created, in case a few characters get left behind
            logger.debug('not creating "%s", as it would be empty', new_path)
            return
        logger.debug('creating "%s"', new_path)

        if p.name == 'requirements.txt':
            packages = {p.strip() for p in text.split('\n') if p.strip() and p.strip() != '#'}
            text = '\n'.join(sorted(packages))
        else:
            # helpful when debugging: print(text.replace(' ', 'ยท').replace('\n', '?\n'))
            if p.suffix == '.py':
                text = SortImports(file_contents=text).output

            regexes = FILES_REGEXES.get(p.suffix, [])
            for regex, repl in regexes:
                text = regex.sub(repl, text)

        # re-add a trailing newline accounting for newlines added by PY_REGEXES
        text = re.sub('\n*$', '\n', text)
        new_path.parent.mkdir(parents=True, exist_ok=True)
        new_path.write_text(text)
        self.files_created += 1 
Example 19
Project: forge   Author: datawire   File: jinja2.py    (license) View Source Project 5 votes vote down vote up
def renders(name, source, **variables):
    """
    Renders a string as a jinja template. The name is used where
    filename would normally appear in error messages.
    """
    try:
        return Template(source, undefined=WarnUndefined).render(**variables)
    except TemplateError, e:
        raise TaskError("%s: %s" % (name, e)) 
Example 20
Project: homeassistant   Author: NAStools   File: template.py    (license) View Source Project 5 votes vote down vote up
def ensure_valid(self):
        """Return if template is valid."""
        if self._compiled_code is not None:
            return

        try:
            self._compiled_code = ENV.compile(self.template)
        except jinja2.exceptions.TemplateSyntaxError as err:
            raise TemplateError(err) 
Example 21
Project: homeassistant   Author: NAStools   File: template.py    (license) View Source Project 5 votes vote down vote up
def async_render(self, variables=None, **kwargs):
        """Render given template.

        This method must be run in the event loop.
        """
        self._ensure_compiled()

        if variables is not None:
            kwargs.update(variables)

        try:
            return self._compiled.render(kwargs).strip()
        except jinja2.TemplateError as err:
            raise TemplateError(err) 
Example 22
Project: forge   Author: datawire   File: jinja2.py    (license) View Source Project 4 votes vote down vote up
def _do_render(env, root, name, variables):
    try:
        return env.get_template(name).render(**variables)
    except TemplateNotFound, e:
        raise TaskError("%s/%s: %s" % (root, name, "template not found"))
    except TemplateError, e:
        raise TaskError("%s/%s: %s" % (root, name, e))