Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jinja filter within a Flask application?

Tags:

flask

jinja2

I am trying to follow this solution, in order to create a datetime filter for my date values inside a template. The advantage of using babel would be the i18n.

I have inserted the code into a file called filter.py in my application package:

from f11_app import app
import babel

def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.format_datetime(value, format)

app.jinja_env.filters['datetime'] = format_datetime  

Now the error I get is:

File "/home/kave/projects/F11/Engineering/f11_app/templates/show_records.html", line 19, in block "body"

<td>{{ record.record_date|datetime }}

File "/home/kave/projects/F11/Engineering/f11_app/filters.py", line 9, in format_datetime

AttributeError: 'module' object has no attribute 'format_datetime'

In order to load the filters.py, the last line of my f11_app's __init__.py is this:

from f11_app import views, filters

What could I be missing please?

like image 229
Houman Avatar asked Jun 09 '13 22:06

Houman


1 Answers

This because babel module didn't have format_datetime method. You must use babel.dates.format_datetime or flask.ext.babel.format_datetime. See: http://babel.edgewall.org/wiki/Documentation/0.9/dates.html and http://pythonhosted.org/Flask-Babel/#formatting-dates.

You also can add filter with decorator:

@app.template_filter('datetime')
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.format_datetime(value, format)
like image 129
tbicr Avatar answered Sep 18 '22 14:09

tbicr