What You'll Learn in This Hour |
|
Django provides a robust library of built-in filters that you can use to manipulate data inside templates. In this hour, you will learn how to use filters to manipulate data that is rendered inside templates.
As you understand and use filters, you will see that they provide several necessary features that are needed when rendering data into HTML responses. The following sections will help you understand filters and how to use them to format text, manipulate lists, sort data, and display dates.
This section discusses how to apply filters in your templates. The filter examples discussed in this section are described in more detail in the following sections.
Each filter is a link to a function in Django's template library that performs a specific task. Filters can be applied in one of two ways—as a direct pipe to a variable, or using the filter tag.
Filters are applied to a variable using piping syntax. For example, to change the variable place to all lowercase, you could apply the lower filter using the following syntax:
{{ place|lower }}
Filters can also be applied to a block of template code or text using the filter tag. The template engine renders whatever is inside the filter block and then applies the filters to it. For example, the following filter tag applies the upper filter to a block of text and the place variable:
{% filter escape|upper %} The meeting will be held at {{ place }}. {% endfilter %}
The Django template engine renders the value of the place variable and then applies the escape and upper filters to the rendered contents.
Either method of applying filters works well. Often, applying the filter directly to a variable is the simplest method. However, using the filter tag is the best method if you need to apply the same filters to a larger amount of data or to a block of text.
Filters can be chained together using the | (pipe) character when applying them to a filter tag or variable. For example, the following filter tag code applies the escape, upper, and linebreaks filters to a block of text:
{% filter escape|upper|linebreaks %} The meeting will be held at {{ place }}. Please be on time. {% endfilter %}
Some filters either allow or require arguments. The syntax for passing arguments to a filter is as follows:
filtername:"argument list"
For example, the following line of code applies the removetags filter to a text variable and passes to it the arguments table, tr, and td:
{{ tableText|removetags:"table tr td" }}
Watch Out!
In the case of the removetags filter, the arguments are space-separated. Some filters require the arguments to be comma-separated. Make sure you know in what format the filter expects the variable list.