Creating custom filters is easy. Filters are really just Python functions that accept either one or two arguments. The first argument is the value to which the filter will be applied. The second argument is the filter argument, if any, that is attached to the filter in the template.
For example, consider the following template code:
{{ "1.2.3.4"|drop:"." }}
The arguments value and arg in the following filter function would be set to 1.2.3.4 and . respectively:
def drop(value, arg): return value.replace(arg, '')
After you have created the filter function, you need to register it with the Library object in the module. To register a filter with a Library object, you call the filter() function of the Library object and pass in the filter name as the first parameter and the filter function as the second:
from django import template register = template.Library() def drop(value, arg): return value.replace(arg, '') register.filter('drop', drop)
Did you Know?
If you are using Python 2.4 or later, you can register the filter using a decorator function. If you do not pass a name argument to the decorator function, the filter function name is used as the filter name. For example, in the following two decorator statements, the name of the filter is DropChar in the first decorator and drop in the second:
@register.filter(name="DropChar") def drop(value, arg): . . . @register.filter() def drop(value, arg):
Did you Know?
If your filter is expecting a string, you can use the @stringfilter decorator for the filter function. The @stringfilter decorator converts objects to their string values before passing them to the filter function. The following code snippet shows an example of using the @stringfilter decorator:
@register.filter(name=" FilterText") @stringfilter def FilterText(value, arg):
Try It Yourself: Create a Custom Template FilterIn this section, you will create a custom template filter to display datetime objects in a specific format without having to use the date filter and filter string. This type of filter can save you keystrokes and time if you have a set way you want datetime objects to be displayed. Follow these steps to create a custom filter module and add the time filter to it:
Listing 13.1. Full Contents of iFriends/Custom/templatetags/custom_filters.py
Listing 13.2. Full Contents of iFriends/templates/Blogs/blog_details.html
|