Before we start writing our own tags and filters, let's review how the built-in ones work. They are written and implemented in the same way that we will use to write our own, so looking at the code and its structure gives us some great examples as a starting point. You can browse the built-in tags and filters by looking at these files in the Django source code:
django/template/defaultfilters.py
django/template/defaulttags.py
If you need to change the way a value outputs in a template, use a template filter. Typical filters modify string and number formats, add or remove characters, and so on. A filter is essentially a Python function that can take one or two arguments: the value it is working on, and an optional argument.
For example, the built-in filter upper
transforms a template string to upper case:
{{ title|upper }}
Behind the scenes, it calls the upper
function in defaultfilters.py
:
def upper(value): """Converts a string into...