本文整理匯總了Python中jinja2.TemplateSyntaxError方法的典型用法代碼示例。如果您正苦於以下問題:Python jinja2.TemplateSyntaxError方法的具體用法?Python jinja2.TemplateSyntaxError怎麽用?Python jinja2.TemplateSyntaxError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2
的用法示例。
在下文中一共展示了jinja2.TemplateSyntaxError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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
示例2: template_exception_handler
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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)
示例3: get_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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])
示例4: load_html_file
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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()
示例5: get_arg_value
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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
示例6: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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)
示例7: test_errors
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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)
示例8: get_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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
示例9: fail
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
def fail(self, message):
raise TemplateSyntaxError(message, self.token.lineno, self.stream.name,
self.stream.filename)
示例10: __init__
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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
示例11: test_undefined
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
def test_undefined(self):
with raises(TemplateSyntaxError):
input_string = "{% huhwhat 'hotel', 'california' %}"
self.render_from_string(input_string, context={})
示例12: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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)
示例13: get_template
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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])
示例14: test_syntax_error
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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'.
''')
示例15: test_regular_syntax_error
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import TemplateSyntaxError [as 別名]
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''')