← All Articles

Custom Jinja template filters in Flask

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

Made with JoyBird