Template Filters
Template filters in Jinja2 let you modify variables before displaying them. Think of them as little functions that transform your data right in the template. They're super handy for formatting dates, changing case, or pretty-printing data.
The basic syntax is variable|filter. You can chain multiple filters together. Here are some common ones:
{{ name|upper }} {# Output: JOHN DOE #}
{{ name|lower }} {# Output: john doe #}
{{ name|capitalize }} {# Output: John doe #}
{{ name|trim }} {# Removes leading/trailing whitespace #}
{{ items|length }} {# Shows number of items #}
{{ text|default('No text') }} {# Shows default if empty #}
The default filter is especially useful. If a variable might be empty or undefined, it provides a fallback value:
{{ user.bio|default('No bio available') }}
For dates, the date filter formats datetime objects nicely:
{{ post.created_at|date:'Y-m-d H:i' }}
{{ post.created_at|date:'F j, Y' }}
When working with complex data like lists or dictionaries, the tojson filter converts them to JSON format. This is great for debugging or passing data to JavaScript:
<script>
var data = {{ user_data|tojson }};
</script>
You can chain filters together to build more complex transformations. The output of one filter becomes the input of the next:
{{ name|trim|upper }} {# First trims whitespace, then makes uppercase #}
{{ text|default('N/A')|truncate(50) }} {# Default then truncate to 50 chars #}
Want your own custom filter? It's easy with @app.template_filter. Just write a function and decorate it:
@app.template_filter('reverse_string')
def reverse_string(s):
return s[::-1]
# Now use it in templates:
{{ "hello"|reverse_string }} {# Output: olleh #}
Filters keep your templates clean. Instead of writing Python logic in the template, you just apply filters. It's the Jinja2 way of doing things.
Try it Yourself ->