Custom Jinja template filters in Flask

Oct 30th, 2016 in Python by Michael Cho

← All articles


A short snippet for creating a template filter, to present datetime objects in Jinja templates.

Flask has a concept of template filters, which allow you to modify the presentation of variables in Jinja templates.

A useful filter I have included in my projects is a custom filter to "pretty print" datetime objects, so a database field like 2016-12-26 14:12:38 can be easily shown as 12/26 for example.

First, add the custom filter to your app:


from myapp import app

@app.template_filter()
def pretty_date(dttm):
    return dttm.strftime("%m/%d")

Alternatively, if you wanted to include this in a Flask Blueprint it would be:


my_blueprint = Blueprint('blue_name', __name__, template_folder='templates')

@my_blueprint.app_template_filter()
def pretty_date(dttm):
    return dttm.strftime("%m/%d")

Then just call it in your template like any of the built-in filters:


# my_template.html
My date is {{ my_object.created_at | pretty_date }}