How to Apply Multiple Filters to a Context Variable in Django

In this article, we show how to apply multiple filters to a context variable in Django.
A context variable is any variable that you pass into a Django template that could represent anything, such as the user's name, birth place, date of birth, credit card number, anything really.
In Django, there are many built-in or pre-built filters that you could use to modify a context variable.
A full list of django's pre-built filters can be found at the following page: https://docs.djangoproject.com/en/5.1/ref/templates/builtins/
Let's for example, take a context variable that represents the the places that a user has visited.
We can apply the title filter to make these places be capitalized for each of the words. This would make an entry such as 'new zealand' or 'New zealand' be 'New Zealand'.
Now let's say in a particular instance, we just want to return the last place that the user visited. To do this, we would apply the last filter, which returns the last item of a list.
Now let's say that we also want to allow for HTML tags to be present in the text unaffected. Maybe there was a bold tag or some type of unique styling done with HTML. We can use the safe filter to allow for HTML and other programming elements such as javascript. This is saying the text is safe.
To add multiple filters in Django to a context variable, all that you have to do is add a '|' separated bye each of the filters.
This will apply all filters to the context variable.
In this case, it will apply the last place that the user visited with each of the words of the place capitalized. If there any HTML tags applied that give the variable special formatting such as a bold tag or italtic tag, these will be brought through because of the safe filter.
If you create your own custom filter correctly, then you add add this in to a context variable as well.
So if we are created a function called highlight_search that takes in a parameter of query into the function, then we can
add this to the context variable filters, such as shown below.
So now we've added our custom filter to the context variable that will highlight any word or words in the place if it matches the query that the user enters.
This example may not make the most sense but it's simply for demonstration purposes that we can add as many filters to a context variable as we'd like. We just have to separate each of the filters with a '|' for all of them to be applied.
And this is how you can add multiple filters to a context variable in Django.
Related Resources
How to Randomly Select From or Shuffle a List in Python