Welcome to our in-depth Flask Template Filters tutorial! In this lesson, we'll learn about Flask's built-in template filters that help us manipulate data before it's rendered in our HTML templates. This is a powerful feature that makes our templates more dynamic and user-friendly.
By the end of this lesson, you'll be able to:
upper, lower, escape, and url_forLet's dive in!
Flask template filters are functions that can be applied to variables within templates to manipulate or transform the data before it's displayed. They are part of the Jinja2 template engine, which is integrated with Flask by default.
Filter functions are called using the | pipe symbol followed by the filter name. For example:
{{ my_variable | filter_name }}The upper and lower filters convert text to uppercase and lowercase, respectively.
Example:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
my_text = 'Hello World!'
return render_template('home.html', my_text=my_text)<!-- templates/home.html -->
<h1>{{ my_text|upper }}</h1>Running this code will display "HELLO WORLD!" as the page title.
The escape filter escapes any special characters in a string to prevent potential cross-site scripting (XSS) attacks.
Example:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
user_input = '<script>alert("XSS Attack!");</script>'
safe_user_input = app.jinja_env.escape(user_input)
return render_template('home.html', user_input=user_input, safe_user_input=safe_user_input)<!-- templates/home.html -->
<p>User Input: {{ user_input }}</p>
<p>Safe User Input: {{ safe_user_input }}</p>The safe_user_input will be displayed safely, without any script tags being executed.
The url_for filter generates URLs based on pre-defined route names.
Example:
# app.py
from flask import Flask, render_template_url_loader, url_for
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')<!-- templates/home.html -->
<a href="{{ url_for('about') }}">About Us</a>In this example, clicking the "About Us" link will take the user to the /about route.
You can create custom filters to extend Flask's functionality. To do this, you'll need to create a function that takes a string as input and returns a modified string as output. Then, you'll register the function with Flask's app.jinja_env.filters dictionary.
Example:
# app.py
from flask import Flask, render_template
from jinja2 import Environment, FileSystemLoader
app = Flask(__name__)
def format_date(value):
# Your custom date formatting function
formatted_date = value.strftime('%B %d, %Y')
return formatted_date
app.jinja_env = Environment(loader=FileSystemLoader('templates'), autoescape=None)
app.jinja_env.filters['format_date'] = format_date
@app.route('/')
def home():
date = datetime.now()
return render_template('home.html', date=date)<!-- templates/home.html -->
<p>Today's date: {{ date|format_date }}</p>In this example, we've created a custom format_date filter that formats a date object into a human-readable format.
Which filter can be used to convert text to uppercase in Flask?
That's it for our Flask Template Filters tutorial! By now, you should have a good understanding of how to use Flask's built-in template filters and even create your own. Happy coding! š
š Remember, practice makes perfect! Try implementing these filters in your own projects and experiment with creating custom filters to make your templates even more dynamic. šÆ