0
0
Flaskframework~5 mins

Template filters in Flask

Choose your learning style9 modes available
Introduction

Template filters help change how data looks before showing it on a webpage. They make your page easier to read and nicer to see.

You want to show a date in a friendly format like 'April 27, 2024' instead of '2024-04-27'.
You need to make text uppercase or lowercase before displaying it.
You want to shorten a long text to just a few words with '...'.
You want to format numbers with commas for thousands.
You want to safely show HTML content without breaking the page.
Syntax
Flask
{{ variable | filter_name }}
Use the pipe symbol (|) to apply a filter to a variable.
You can chain multiple filters like {{ variable | filter1 | filter2 }}.
Examples
This changes the text in name to all uppercase letters.
Flask
{{ name | upper }}
This rounds the number in price to 2 decimal places.
Flask
{{ price | round(2) }}
This shortens description to 20 characters and adds '...'.
Flask
{{ description | truncate(20) }}
This renders the HTML content in html without escaping it.
Flask
{{ html | safe }}
Sample Program

This Flask app shows how to use template filters to change text and numbers before showing them on the page. The user's name is uppercase, the balance is rounded to 2 decimals, and the bio is shortened.

Flask
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def home():
    user = {'name': 'Alice', 'balance': 12345.6789, 'bio': 'Loves programming and coffee.'}
    template = '''
    <h1>Hello, {{ user.name | upper }}!</h1>
    <p>Your balance is ${{ user.balance | round(2) }}</p>
    <p>About you: {{ user.bio | truncate(15) }}</p>
    '''
    return render_template_string(template, user=user)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Filters are easy to chain for multiple changes.

You can create your own custom filters if needed.

Use filters to keep your templates clean and your Python code simple.

Summary

Template filters change how data looks in your webpage.

Use the pipe symbol (|) to apply filters in templates.

Common filters include upper, round, truncate, and safe.