Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Babel how to use translation in Jinja template file

In my Flask application, in main.py file, I defined:

from flaskext.babel import gettext
....
def somefun():
    return render_template('some.html', messages=messages)

in template file some.html, I used:

<input type='text' name='keywords' value='{{ keywords|default('') }}' placeholder='{{ gettext('Search...') }}' />

This gives an error:

<input type='text' name='keywords' value='{{ keywords|default('') }}' placeholder='{{ gettext('Search...') }}' />
UndefinedError: 'gettext' is undefined

How to import this function for template use?

like image 851
Brent Jiang Avatar asked Mar 01 '12 11:03

Brent Jiang


1 Answers

Unfortunately this is not documented at all, but Flask-Babel is transparently using Jinja2's i18n extension. This means that by default, following functions for expressions are available: gettext, ngettext and _.

There's also possibility to use template tags:

{% trans %}foo{% endtrans%}

{% trans num %}
There is {{ num }} object.
{% pluralize %}
There are {{ num }} objects.
{% endtrans %}

And the bug report about missing docs that's waiting for patches ;)

like image 87
plaes Avatar answered Oct 07 '22 03:10

plaes