Difference between jinja2 functions and filters?

I am writing some functions to do things like format dates and text in my templates.

def coolfunc(s): return s + ' is cool' app.jinja_env.globals.update(coolfunc=coolfunc) app.jinja_env.filters['coolfunc'] = coolfunc 

template:

 {{ coolfunc(member.name) }} {{ member.name | coolfunc }} 

exit:

 John is cool John is cool 

I am not sure what the real difference between functions and filters is. It seems to me that the filters just look cleaner?

+8
python flask jinja2
source share
1 answer

The difference is that filters can have special access to the Environment or Context , but regular (global) functions cannot; in particular, contextfilter and friends. This can be useful for performing context-sensitive things such as localization and formatting, regardless of global state.

http://jinja.pocoo.org/docs/api/#utilities

+8
source share

All Articles