How to get a specific language translation using pybabel

Viewed 1109

Most of the time, using Babel's gettext() or _() is with a current locale set within the current context, so that the target language is implicit, it is not passed as an argument to gettext().

However, is there a way to get the translation of a phrase in a given target language, such as:

message = gettext('Hello there', language='es')

The original gettext does not have this possibility, but is there any other API that would achieve this ?

2 Answers

If you're using the plain gettext API, use environment variables:

import os

os.environ['LANGUAGE'] = 'en'
message = gettext('Hello there')

For OO gettext it goes like this:

import gettext

fr = gettext.translation('yourdomain', languages=['fr'])
es = gettext.translation('yourdomain', languages=['es'])

fr.install()
// use French ...
es.install()
// use Spanish ...

If you are using Flask-Babel, you can use force_locale from its Low-Level API:

from flask_babel import force_locale

with force_locale('en_US'):
    send_email(gettext('Hello!'), ...)
Related