Skip to content

Custom Filters

When built-in filters aren’t enough, you can create custom ones.

Register a custom filter

from flask import Flask
 
app = Flask(__name__)
 
 
def format_username(value: str) -> str:
    return value.strip().title()
 
 
app.jinja_env.filters["format_username"] = format_username
from flask import Flask
 
app = Flask(__name__)
 
 
def format_username(value: str) -> str:
    return value.strip().title()
 
 
app.jinja_env.filters["format_username"] = format_username

Use it in templates:

<p>{{ username | format_username }}</p>
<p>{{ username | format_username }}</p>

Alternative: decorator style

Flask also supports:

@app.template_filter("format_username")
def format_username(value):
    return value.strip().title()
@app.template_filter("format_username")
def format_username(value):
    return value.strip().title()

When to use custom filters

  • formatting dates
  • truncating text in a consistent way
  • normalizing usernames/display names

If the same template logic repeats, it’s a good candidate for a filter.

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did