- exception
jinja2. UndefinedError (message=None) Raised if a template tries to operate on Undefined .
- exception
jinja2. TemplateNotFound (name, message=None) Raised if a template does not exist.
- exception
jinja2. TemplatesNotFound (names=(), message=None) Like TemplateNotFound but raised if multiple templates are selected. This is a subclass of TemplateNotFound exception, so just catching the base exception will catch both.
- exception
jinja2. TemplateSyntaxError (message, lineno, name=None, filename=None) Raised to tell the user that there is a problem with the template. message 错误信息的 utf-8 字节串。
lineno 发生错误的行号。
name 模板的加载名的 unicode 字符串。
filename 加载的模板的文件名字节串,以文件系统的编码(多是 utf-8 , Windows 是 mbcs )。
文件名和错误消息是字节串而不是 unicode 字符串的原因是,在 Python 2.x 中,不对异常和回溯使用 unicode ,编译器同样。这会在 Python 3 改变。
- exception
jinja2. TemplateAssertionError (message, lineno, name=None, filename=None) Like a template syntax error, but covers cases where something in the template caused an error at compile time that wasn’t necessarily caused by a syntax error. However it’s a direct subclass of TemplateSyntaxError and has the same attributes.
自定义过滤器自定义过滤器只是常规的 Python 函数,过滤器左边作为第一个参数,其余的参数作 为额外的参数或关键字参数传递到过滤器。 例如在过滤器 {{ 42|myfilter(23) }} 中,函数被以 myfilter(42, 23) 调 用。这里给出一个简单的过滤器示例,可以应用到 datetime 对象来格式化它们: def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
你可以更新环境上的 filters 字典来把它注册到模板环境上: environment.filters['datetimeformat'] = datetimeformat
在模板中使用如下: written on: {{ article.pub_date|datetimeformat }}
publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
也可以传给过滤器当前模板上下文或环境。当过滤器要返回一个未定义值或检查当前的 autoescape 设置时很有用。为此,有三个装饰器: environmentfilter() 、 contextfilter() 和 evalcontextfilter() 。 这里是一个小例子,过滤器把一个文本在 HTML 中换行或分段,并标记返回值为安全 的 HTML 字符串,因为自动转义是启用的: import re
from jinja2 import evalcontextfilter, Markup, escape
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
for p in _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
上下文过滤器工作方式相同,只是第一个参数是当前活动的 Context 而 不是环境。
|