Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 450
Patrick Yan Avatar asked Mar 18 '14 21:03

Patrick Yan


1 Answers

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

like image 113
SingleNegationElimination Avatar answered Sep 16 '22 18:09

SingleNegationElimination