2

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 ?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
patb
  • 1,688
  • 1
  • 17
  • 21

2 Answers2

0

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 ...
Guido Flohr
  • 1,871
  • 15
  • 28
  • Thanks, this might help some people, but in my case I'm in a web server multi-user environment using Flash, so I doubt the os.environ trick would do it. Actually there are tricks to switch locale in Flask via `ctx = _request_ctx_stack.top` then `ctx.babel_locale = Locale.parse(language)`, but I was looking for a true API to babel, with locale as argument. – patb Oct 16 '18 at 16:14
  • The os.environ trick should work everywhere. An API call with the locale as an argument is very unlikely to exist because the underlying C API does not have anything like that, and that is on purpose. – Guido Flohr Oct 17 '18 at 09:18
0

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!'), ...)
bagonyi
  • 3,258
  • 2
  • 22
  • 20