String filters
In Exercise 11.01, Creating a custom template filter, we built a custom filter, which allowed us to split a provided string with a separator and generate a list from it. This filter can take any kind of variable and split it as a list of values based on a delimiter provided. But what if we wanted to restrict our filter to work only with strings and not with any other type of values, such as integers?
We can use the stringfilter
decorator provided by Django’s template library to develop filters that work only on strings. When the stringfilter
decorator is used to register a Python method as a filter in Django, the framework ensures that the value being passed to the filter is converted to a string before the filter executes. This reduces any potential issues that may arise when non-string values are passed to our filter.
The steps to implement a string filter are similar to the ones we followed for building a custom filter with some minor changes.
Remember...