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:

  1. def datetimeformat(value, format='%H:%M / %d-%m-%Y'):
  2. return value.strftime(format)

You can register it on the template environment by updating thefilters dict on the environment:

  1. environment.filters['datetimeformat'] = datetimeformat

Inside the template it can then be used as follows:

  1. written on: {{ article.pub_date|datetimeformat }}
  2. 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:

  1. import re
  2. from jinja2 import evalcontextfilter
  3. from markupsafe import Markup, escape
  4. _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
  5. @evalcontextfilter
  6. def nl2br(eval_ctx, value):
  7. result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))
  8. for p in _paragraph_re.split(escape(value)))
  9. if eval_ctx.autoescape:
  10. result = Markup(result)
  11. return result

Context filters work the same just that the first argument is the currentactive Context rather than the environment.