Improve your experience at WBO. You should consider allowing javascript, cookies and loading of external resources from third-party sites.

Create Jinja2 template filters in Flask

A filter alters a variable in a template. It's mostly for formatting purpose. In the template, it's separated from the variable by a pipe character (|). See Template Designer Documentation for details. There's a bunch of builtin filters, covering a wide range of cases. But sometimes, you may need more. Fortunately, it's pretty easy to add new Jinja2 filters in Flask.

First, let's see how to define a date formatting filter. The filter is a function with a lesat an argument, the value to modify. We want a convenient filter, so let's add an optional format string, with '%c' as default value.

1
2
3
4
5
6
7
8
def _jinja2_filter_datetime(date, fmt='%c'):
    # check whether the value is a datetime object
    if not isinstance(date, (datetime.date, datetime.datetime)):
        try:
            date = datetime.datetime.strptime(str(date), '%Y-%m-%d').date()
        except Exception, e:
            return date
    return date.strftime(fmt)

Nothing weird or magic.

Then the function is declared as a filter in the Flask application, under the name 'datetime'.

1
2
3
4
5
from flask import Flask
app = Flask(__name__)

# add our function to the filters of the jinja2 environment
app.jinja_env.filters['datetime'] = _jinja2_filter_datetime

Now, it is usable in a template:

1
2
3
4
<p>{{ a_date|datetime }}</p>
        --> Thu May 10 20:59:06 2012
<p>{{ a_date|datetime('%d.%m.%Y')}}</p>
        --> 10.05.2012
back to top