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 }}
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 }}
{{ "hello world"|upper }}
{{ my_date|date:"D d M Y" }}
{{ "This is a long sentence."|truncatechars:10 }}
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 }}
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 }}
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.