Question

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

output:

John is cool
John is cool

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

Was it helpful?

Solution

The difference is that filters can have special access to the Environment or Context, but regular (global) functions cannot; specifically, there's contextfilter and friends. This can be useful for doing context sensitive things like localization and formatting, without depending on global state.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top