Skip to Content
Mastering Flask Web Development - Second Edition
book

Mastering Flask Web Development - Second Edition

by Daniel Gaspar, Jack Stouffer
October 2018
Intermediate to advanced
332 pages
8h 9m
English
Packt Publishing
Content preview from Mastering Flask Web Development - Second Edition

Custom filters

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Flask Web Development, 2nd Edition

Flask Web Development, 2nd Edition

Miguel Grinberg
Flask Web Development

Flask Web Development

Miguel Grinberg

Publisher Resources

ISBN: 9781788995405Supplemental Content