October 2018
Intermediate to advanced
332 pages
8h 9m
English
Adding your own filter into Jinja is as simple as writing a Python function. To understand custom filters, we will look at an example. Our simple filter will count the number of occurrences of a substring in a string and return this figure. Look at the following call:
{{ variable | count_substring("string") }}
We need to write a new Python function with the following signature, where the first argument is the piped variable:
def count_substring(variable, sub_string)
We can define our filter as the following:
@app.template_filterdef count_substring(string, sub_string): return string.count(sub_string)
To add this function to the list of available filters on Jinja2, we have to register it and add it to the filters dictionary ...