Skip to content

Instantly share code, notes, and snippets.

@Xion
Created August 23, 2015 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xion/47c85671cdfb481fd925 to your computer and use it in GitHub Desktop.
Save Xion/47c85671cdfb481fd925 to your computer and use it in GitHub Desktop.
ErrorExtension for Jinja
"""
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