Custom Filters
Custom filters are just regular Python functions that take the left side ofthe filter as first argument and the arguments passed to the filter asextra arguments or keyword arguments.
For example in the filter {{ 42|myfilter(23) }}
the function would becalled with myfilter(42, 23)
. Here for example a simple filter that canbe applied to datetime objects to format them:
def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
return value.strftime(format)
You can register it on the template environment by updating thefilters
dict on the environment:
environment.filters['datetimeformat'] = datetimeformat
Inside the template it can then be used as follows:
written on: {{ article.pub_date|datetimeformat }}
publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}
Filters can also be passed the current template context or environment. Thisis useful if a filter wants to return an undefined value or check the currentautoescape
setting. For this purpose three decoratorsexist: environmentfilter()
, contextfilter()
andevalcontextfilter()
.
Here a small example filter that breaks a text into HTML line breaks andparagraphs and marks the return value as safe HTML string if autoescaping isenabled:
import re
from jinja2 import evalcontextfilter
from markupsafe import 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', Markup('<br>\n'))
for p in _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
Context filters work the same just that the first argument is the currentactive Context
rather than the environment.