Created
August 23, 2015 16:33
-
-
Save Xion/47c85671cdfb481fd925 to your computer and use it in GitHub Desktop.
ErrorExtension for Jinja
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Jinja extension adding support for {% error %} tag | |
that allows to raise exceptions directly from templates. | |
""" | |
from jinja2 import TemplateAssertionError | |
from jinja2.ext import Extension | |
from jinja2.nodes import CallBlock, Const | |
class ErrorExtension(Extension): | |
"""Extension providing {% error %} tag, allowing to raise errors | |
directly from a Jinja template. | |
""" | |
tags = frozenset(['error']) | |
def parse(self, parser): | |
"""Parse the {% error %} tag, returning an AST node.""" | |
tag = parser.stream.next() | |
message = parser.parse_expression() | |
node = CallBlock( | |
self.call_method('_exec_error', [message, Const(tag.lineno)]), | |
[], [], []) | |
node.set_lineno(tag.lineno) | |
return node | |
def _exec_error(self, message, lineno, caller): | |
"""Execute the {% error %} statement, raising an exception.""" | |
raise TemplateUserError(message, lineno) | |
class TemplateUserError(TemplateAssertionError): | |
"""Exception raised in the template through the use of {% error %} tag.""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment