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 ?

2 Answers 2

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 ...
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
@GuidoFlohr that seems like such a crazy system. How is an OS variable baked so deep in the code, instead of being one of the ways the language can be selected, of several!?
@RobGrant, the idea behind that is consistency so that number formats, dates, and messages all match. That makes a lot of sense for desktop applications but not so much for web applications. But I hear you, and this is why the gettext implementations that I have written - libintl-perl for Perl and esgettext for TypeScript/JavaScript - also allow you to simply hardcode the language, resp. the locale identifier, assuming that you know which locales are supported by your application.
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!'), ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.