< RETRO BLOG >

Flask Recipe: Jinja2 Template Filters

by jpk on 2018-12-24 09:37:44 edited on 2018-12-25 10:24:09

Flask Recipe: Jinja2 Template Filters

This post covers a simple Python recipe to programmatically make all filters available to your templates in your flask app.

The code utils/filters.py contains a function called init_app(), when it is called it will look through all globally accessible objects. When a function name starts with a filter_ it will be added as template filter for you to use in the Jinja2 templates.

 1 from datetime import datetime
 2 
 3 
 4 def filter_utcfromtimestamp(timestamp):
 5     return datetime.utcfromtimestamp(int(timestamp))
 6 
 7 
 8 def filter_caps(text):
 9     return text.upper()
10 
11 
12 def filter_foo(text):
13     return text.replace('foo', 'bar')
14 
15 
16 def init_app(app):
17     for func in globals():
18         if func.startswith('filter_'):
19             name = func.split('_')[-1]
20             app.add_template_filter(globals()[func], name)

The above code defines three filters which will be avaiable after intitialization:

  • utcfromtimestamp: converts a unix timestamp to a human readable format. Sample: {{ 398044800|utcfromtimestamp }} outputs 2018-08-13 00:00:00
  • caps: convert a string into upper case. Sample: {{ 'foo'|caps }} outputs FOO
  • foo: replace foo with bar. Sample: {{ 'foobar'|foo }} outputs barbar

To intitialize and register the filters you can call the function as shown in the sample create_app() function below.

 1 from flask import Flask
 2 # [...]
 3 def create_app(test_config=None):
 4     app = Flask(__name__)
 5     # [...]
 6     from .utils import filters
 7     filters.init_app(app)
 8     # [...]
 9     return app