Flask Template Filters Tutorial šŸŽÆ

beginner
24 min

Flask Template Filters Tutorial šŸŽÆ

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:

  • Understand the purpose of template filters in Flask
  • Use common Flask template filters like upper, lower, escape, and url_for
  • Write custom filters to extend Flask's functionality
  • Apply filters to variables and expressions in your templates

Let's dive in!

What are Flask Template Filters? šŸ“

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:

html
{{ my_variable | filter_name }}

Common Flask Template Filters šŸ’”

Upper and Lower

The upper and lower filters convert text to uppercase and lowercase, respectively.

Example:

python
# 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)
html
<!-- templates/home.html --> <h1>{{ my_text|upper }}</h1>

Running this code will display "HELLO WORLD!" as the page title.

Escape

The escape filter escapes any special characters in a string to prevent potential cross-site scripting (XSS) attacks.

Example:

python
# 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)
html
<!-- 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.

url_for

The url_for filter generates URLs based on pre-defined route names.

Example:

python
# 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')
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.

Custom Filters šŸ’”

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:

python
# 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)
html
<!-- 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.

Quiz šŸ“

Quick Quiz
Question 1 of 1

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. šŸŽÆ