Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Django Template Filters Tutorial

Introduction

Template filters in Django allow you to modify variables in the template before they are rendered to the final HTML output. They are simple functions that take a value, modify it, and return the modified value. Understanding how to use these filters can greatly enhance the way you display data in your templates.

Basic Usage

To use a template filter, you apply it to a variable within double curly braces and use a pipe symbol (|) followed by the filter name. For example:

{{ my_variable|filter_name }}

Let’s look at a simple example where we use the lower filter to convert a string to lowercase:

{{ "HELLO WORLD"|lower }}
hello world

Common Built-in Filters

Django comes with a variety of built-in filters. Here are a few commonly used ones:

  • length: Returns the length of the value.
  • upper: Converts a string to uppercase.
  • date: Formats a date according to the given format string.
  • truncatechars: Truncates a string after a certain number of characters.

Examples

{{ my_list|length }}
5
{{ "hello world"|upper }}
HELLO WORLD
{{ my_date|date:"D d M Y" }}
Mon 01 Jan 2023
{{ "This is a long sentence."|truncatechars:10 }}
This is a...

Chainable Filters

You can also chain multiple filters together. The output of one filter is passed as the input to the next filter. This can be useful for formatting data in multiple ways:

{{ "hello world"|upper|truncatechars:5 }}
HELLO...

Custom Filters

If the built-in filters do not meet your needs, you can create custom filters. To create a custom filter, you need to define a Python function and register it using Django's template library.

Example

First, create a file called templatetags/custom_filters.py:

from django import template

register = template.Library()

@register.filter(name='reverse')
def reverse(value):
    return value[::-1]
                    

Then, load the custom filter in your template and use it:

{% load custom_filters %}
{{ "hello"|reverse }}
olleh

Conclusion

Template filters are a powerful feature in Django that allow you to manipulate data directly in your templates. By understanding and utilizing both built-in and custom filters, you can create more dynamic and user-friendly web applications. Experiment with different filters and see how they can improve your templates.