Template filters help change how data looks before showing it on a webpage. They make your page easier to read and nicer to see.
Template filters in Flask
Introduction
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
name to all uppercase letters.Flask
{{ name | upper }}price to 2 decimal places.Flask
{{ price | round(2) }}description to 20 characters and adds '...'.Flask
{{ description | truncate(20) }}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)
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.
Practice
1. What does the
| upper filter do in a Flask template?easy
Solution
Step 1: Understand the purpose of the
Theupperfilterupperfilter changes all letters in a string to uppercase.Step 2: Compare with other filters
Other filters likeround,truncate, and date formatting do different tasks unrelated to letter case.Final Answer:
Converts the text to uppercase letters -> Option DQuick Check:
upper= uppercase text [OK]
Hint: Remember: upper means all caps text [OK]
Common Mistakes:
- Confusing upper with round or truncate
- Thinking upper formats dates
- Using upper on numbers expecting rounding
2. Which of the following is the correct syntax to apply the
round filter to a variable price in a Flask template?easy
Solution
Step 1: Recall Flask template filter syntax
Filters are applied using the pipe symbol|followed by the filter name and optional arguments in parentheses.Step 2: Identify the correct syntax for
The correct syntax isround{{ price | round(2) }}. Other options either misuse method call syntax or wrong separator.Final Answer:
{{ price | round(2) }} -> Option AQuick Check:
Filter syntax uses pipe and parentheses [OK]
Hint: Use pipe (|) then filter name with parentheses [OK]
Common Mistakes:
- Using dot notation like a method call
- Using colon instead of parentheses for arguments
- Calling Python functions directly inside templates
3. Given this Flask template snippet:
What will be the output rendered on the webpage?
{{ 'hello world' | truncate(8) }}What will be the output rendered on the webpage?
medium
Solution
Step 1: Understand the
Thetruncatefilter behaviortruncate(8)filter shortens the string to 8 characters including the ellipsis....Step 2: Calculate the truncated output
It keeps 5 characters from the original string and adds...to make total length 8: "hello wo" + "..." = "hello wo...".Final Answer:
hello wo... -> Option BQuick Check:
truncate(8) = 5 chars + ... [OK]
Hint: truncate(n) includes ... in total length n [OK]
Common Mistakes:
- Ignoring the ellipsis length
- Assuming truncate cuts exactly n characters
- Confusing truncate with slice or substring
4. What is wrong with this Flask template code?
It causes an error when rendering. Why?
{{ username | upper() }}It causes an error when rendering. Why?
medium
Solution
Step 1: Check filter usage syntax
Filters without arguments should be used without parentheses, like{{ username | upper }}.Step 2: Identify the cause of error
Using parentheses without arguments causes a syntax error in Flask templates.Final Answer:
Filters should not have parentheses when no arguments are passed -> Option CQuick Check:
No parentheses for no-arg filters [OK]
Hint: No parentheses for filters without arguments [OK]
Common Mistakes:
- Adding empty parentheses to filters
- Thinking all filters require parentheses
- Confusing filters with Python function calls
5. You want to display a date variable
post_date in your Flask template as "April 05, 2024". Which filter usage is correct to achieve this format?hard
Solution
Step 1: Identify the correct Flask template filter for date formatting
Thedatefilter formats dates using Python'sstrftimeformat codes.Step 2: Match the format string to desired output
The format'%B %d, %Y'produces "April 05, 2024". Other options use incorrect filter names or format styles.Final Answer:
{{ post_date | date('%B %d, %Y') }} -> Option AQuick Check:
Date filter + strftime format = {{ post_date | date('%B %d, %Y') }} [OK]
Hint: Use date filter with Python strftime format [OK]
Common Mistakes:
- Using non-existent filters like format_date
- Confusing JavaScript date formats with Python
- Using strftime filter which Flask does not provide
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
