Jinja2 template datetime filters in Flask

Well, I'm really liking Flask for the moment. It's light, convenient and well documented. Also, Jinja2 is quite powerful and things are building up pretty fast.

A filter alters a variable in a template. It's mostly for formatting purpose. In the template, it's separated from the variable by a pipe character (|). See Template Designer Documentation for details. There's a bunch of builtin filters, covering a wide range of cases. But sometimes, you may need more. Fortunately, it's pretty easy to add new Jinja2 filters in Flask.

In Jinja2 a filter is a block of code that is applied on user demand on a given variable in a template.

 See Template Designer Documentation for details. There's a bunch of builtin filters, for many different things. In our task at hand, we don't have a filter to localize dates, so let's build one.

First, you need to have Flask-Babel up and running. Next we will create our filter:


On your Jinja2 templates, you only need a datetime and apply the date filter:

{{ obj.date | date }}

Or pass it a different format

{{ obj.date | date(_('%%Y.%%m.%%d')) }}

The only "magical" parts here is the gettext('%%m/%%d/%%Y') and _('%%Y.%%m.%%d'). Now you can add to your different .po files the different formats to use for each language.


No hay comentarios:

Publicar un comentario