Custom Jinja template filters in Flask

Oct 30th, 2016 in  by Michael Cho

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 }}


Other articles you may like

Python command-line scripts with argparse
Feb 15th, 2018
SQLAlchemy commit(), flush(), expire(), refresh(), merge() - what's the difference?
Nov 2nd, 2017
Prioritized Code Review Checklist - what to look for first, second, and last
Sep 21st, 2017
Many to many relationships in SQLAlchemy models (Flask)
Jul 28th, 2017
Bash script to relink alembic migrations
Jun 12th, 2017