Differences

This shows you the differences between two versions of the page.

Link to this comparison view

blog:flask_register_all_template_filters_in_one_module [2018/12/17 13:49] (current)
jpk created
Line 1: Line 1:
 +====== Flask register all template filters in one module ======
 +During my tests with [[http://​flask.pocoo.org/​|Flask]],​ the python web framework, I stumbled upon the challenge to register all my filters I had stored in ''​app/​util/​filters.py''​.
 +
 +My solution is the ''​def init_app(app)''​ function:
 +<code python>
 +def filter_upper(text):​
 +    return text.upper()
 +
 +
 +def filter_lower(text):​
 +    return text.lower()
 +
 +
 +def init_app(app):​
 +    for func in globals():
 +        if func.startswith('​filter_'​):​
 +            name = func.split('​_'​)[-1]
 +            app.add_template_filter(globals()[func],​ name)
 +</​code>​
 +
 +The ''​init_app''​ function will search through all global members of the module for function definitions where the name starts with ''​filter_''​. These functions are than registered to the flask app. The name of the filter is automatically generated from the function name.
 +
 +~~LINKBACK~~
 +~~DISCUSSION~~
  
Last modified: le 2018/12/17 13:49