Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

How to Decorate Imported Libs in Python for Jinja Template Filters in Flask


To decorate an imported function in Python you would do something like this

# in ./lib.py
def function_name():
    # function body

And then in your program you could decorate it like this

from lib import function_name
function_name = decorator_expression(function_name)

It's a little different in Flask because we have an app context.

Normally, you would create a custom filter like this

app = Flask(__name__)
def function_name():
    # do something

To accomplish the same end result with custom filters that are imported, we will register our custom filter in jinja_env.filters

from flask import Flask
from lib import function_name

app = Flask(__name__)
app.jinja_env.filters['function_name'] = function_name

This will let us use our function_name filter in our templates

If have a lot of filters you could loop over an array like so

for f in [function_name, other_function_name]:
    app.jinja_env.filters[f.__name__] = f

Using the __name__ method on the function gives us the method name as a string that will be available as our template filter.

We could use it in templates the same way

{{'hello world' | function_name}}
Tagged w/ #python #flask #web development #jinja #templates #dynamic programming