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

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')

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

Primer to Python multiprocessing, multithreading, and asyncio
Oct 24th, 2018
Method delegation in Python
Jul 11th, 2018
Using Python enums in SQLAlchemy models
May 16th, 2018
Python command-line scripts with argparse
Feb 15th, 2018
SQLAlchemy commit(), flush(), expire(), refresh(), merge() - what's the difference?
Nov 2nd, 2017