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_usernamefrom flask import Flask
app = Flask(__name__)
def format_username(value: str) -> str:
return value.strip().title()
app.jinja_env.filters["format_username"] = format_usernameUse 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 coffeeWas this page helpful?
Let us know how we did
