Take a look at how I solved Jinja2 filters structure with my Flask Boilerplate.
Jinja Customization.
Flask uses Jinja2 as a template engine. Although you are free to use any other template engine, Jinja2 is a de-facto industry standard. In this post, I'll talk about filters. Jinja2 has a list of built-in filters, and Flask leverages them. For example, when you want to capitalize a string:
<p>{{ name|capitalize }}</p>
This way
<p>{{ name|default("Robot") }}</p>
If you want to register your filter there are two ways to do this in Flask. You can either use template_filter decorator, or you can put them to jinja_env. Decorators can be defined app-wise or at the blueprint level. I prefer to define filters globally via jinja_env.
def locale_code_to_name_filter(locale_code: str) -> str:
if locale_code == "en_us":
return "English (US)"
return locale_code
app.jinja_env.filters['lc_name'] = locale_code_to_name_filter
@app.template_filter("lc_name")
def locale_code_to_name_filter(locale_code: str) -> str:
if locale_code == "en_us":
return "English (US)"
return locale_code
Then in your templates:
<p>{{ locale|lc_name }}</p>