Everything you need as a full stack developer

Flask Filters with custom template filters

- Posted in Flask by

TL;DR Flask's built-in filters can be extended with custom filters using the @app.template_filter decorator. A practical example of a custom filter is converting bytes to human-readable size, which can be applied in templates like any other built-in filter: {{ file_size|human_readable_size }}.

Unlocking Power in Flask: Custom Template Filters with Flasks's Built-in Filters

As a Fullstack Developer working on Flask projects, you're likely familiar with its robust feature set and ease of use. However, there are always ways to optimize and refine your code for better performance and maintainability. One often overlooked yet incredibly powerful feature is the ability to create custom template filters.

In this article, we'll explore how to leverage Flask's built-in filters and extend them with our own custom filters. We'll dive into practical examples, demonstrating real-world applications of these concepts.

Flask's Built-in Filters: A Primer

Before diving into custom filters, it's essential to understand what built-in filters are available in Flask. Some notable examples include:

  • strftime: Formats dates according to a specified format string
  • tojson: Converts a Python object to JSON
  • striptags: Strips HTML tags from a string

You can apply these filters using the following syntax: {{ variable|filter }}. For instance, to display a date in a specific format, you would use {{ date_of_birth|strftime('%Y-%m-%d') }}.

Creating Custom Template Filters

Now that we've covered Flask's built-in filters, let's create our own custom filter. We'll start by defining a simple function that will serve as the basis for our filter:

from flask import Flask

app = Flask(__name__)

def human_readable_size(size_in_bytes):
    """
    Converts bytes to human-readable size (e.g., KB, MB, GB)
    """
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_in_bytes < 1024.0:
            return f"{size_in_bytes:.2f} {unit}"
        size_in_bytes /= 1024.0
    return f"{size_in_bytes:.2f} TB"

Next, we need to register our custom filter with Flask using the @app.template_filter decorator:

@app.template_filter('human_readable_size')
def human_readable_size(size_in_bytes):
    return human_readable_size(size_in_bytes)

Now you can use this custom filter in your templates like any other built-in filter: {{ file_size|human_readable_size }}.

Advanced Example: Using Multiple Arguments

In some cases, it's necessary to pass multiple arguments to a custom filter. Let's create an example where we'll implement a filter that formats phone numbers:

@app.template_filter('format_phone_number')
def format_phone_number(phone_number, country_code):
    return f"{country_code} {phone_number}"

To use this filter, simply call it with both arguments in the template: {{ user.phone_number|format_phone_number(country_code) }}.

Best Practices and Gotchas

When creating custom filters, remember to:

  • Keep your filter functions simple and focused on a single task
  • Use descriptive names for your filters to avoid confusion
  • Test your filters thoroughly with various inputs

Additionally, be aware that custom filters are applied after all other template filtering, so if you're modifying data in another part of the template loop, it might interact with your custom filter's behavior.

In conclusion, custom template filters can significantly enhance the maintainability and flexibility of your Flask applications. By leveraging these techniques, you'll be able to create more efficient, readable, and user-friendly templates that deliver exceptional performance.

Fullstackist aims to provide immersive and explanatory content for full stack developers Fullstackist aims to provide immersive and explanatory content for full stack developers
Backend Developer 103 Being a Fullstack Developer 107 CSS 109 Devops and Cloud 70 Flask 108 Frontend Developer 357 Fullstack Testing 99 HTML 171 Intermediate Developer 105 JavaScript 206 Junior Developer 124 Laravel 221 React 110 Senior Lead Developer 124 VCS Version Control Systems 99 Vue.js 108

Recent Posts

Web development learning resources and communities for beginners...

TL;DR As a beginner in web development, navigating the vast expanse of online resources can be daunting but with the right resources and communities by your side, you'll be well-equipped to tackle any challenge that comes your way. Unlocking the World of Web Development: Essential Learning Resources and Communities for Beginners As a beginner in web development, navigating the vast expanse of online resources can be daunting. With so many tutorials, courses, and communities vying for attention, it's easy to get lost in the sea of information. But fear not! In this article, we'll guide you through the most valuable learning resources and communities that will help you kickstart your web development journey.

Read more

Understanding component-based architecture for UI development...

Component-based architecture breaks down complex user interfaces into smaller, reusable components, improving modularity, reusability, maintenance, and collaboration in UI development. It allows developers to build, maintain, and update large-scale applications more efficiently by creating independent units that can be used across multiple pages or even applications.

Read more

What is a Single Page Application (SPA) vs a multi-page site?...

Single Page Applications (SPAs) load a single HTML file initially, handling navigation and interactions dynamically with JavaScript, while Multi-Page Sites (MPS) load multiple pages in sequence from the server. SPAs are often preferred for complex applications requiring dynamic updates and real-time data exchange, but MPS may be suitable for simple websites with minimal user interactions.

Read more