Python jinja2 模块,TemplateError() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用jinja2.TemplateError()

项目:qface    作者:Pelagicore    | 项目源码 | 文件源码
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)
项目:ivy    作者:dmulholland    | 项目源码 | 文件源码
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)
项目:forge    作者:datawire    | 项目源码 | 文件源码
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))
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
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
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
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)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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)
项目:pyetje    作者:rorlika    | 项目源码 | 文件源码
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)
项目:constructor    作者:conda    | 项目源码 | 文件源码
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
项目:NetOpsWorkshop    作者:ipspace    | 项目源码 | 文件源码
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
项目:NetOpsWorkshop    作者:ipspace    | 项目源码 | 文件源码
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
项目:NetOpsWorkshop    作者:ipspace    | 项目源码 | 文件源码
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?")
项目:NetOpsWorkshop    作者:ipspace    | 项目源码 | 文件源码
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
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
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)
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
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)
项目:jupyterlab_launcher    作者:jupyterlab    | 项目源码 | 文件源码
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
            )
项目:mistral-lint    作者:d0ugal    | 项目源码 | 文件源码
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))
项目:kibitzr    作者:kibitzr    | 项目源码 | 文件源码
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
项目:feedstockrot    作者:axiom-data-science    | 项目源码 | 文件源码
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
项目:aiohttp-devtools    作者:aio-libs    | 项目源码 | 文件源码
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
项目:forge    作者:datawire    | 项目源码 | 文件源码
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))
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
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)
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
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)