Using Python functions from within your template with Jinja2 filters
With if
-clauses, loops, and the ability to pass variables into our template, we can now handle a lot of logic from right within our template file. But while the logic of Jinja2 can be quite expressive, there are limits to what you can achieve with it. Sometimes it might be easier to just use a Python function instead.
Jinja2 allows you to call custom functions on their variables to change the output of that variable. This concept is called filters and the template language itself already comes with some filters such as length
that can be used to determine the length of a list that was passed into the template.
In this recipe, we are going to see how you can write your own Python function that can be called as a filter. In this example, we are going to write a simple function that takes an IPv4 address and converts this address in to its IPv6 equivalent using Python's built-in ipaddress
module.