Al Nikolaj
Al Nikolaj

Reputation: 315

How to get specific string translation which is not currently the locale?

Let's say I have a string in English, locale="en", e.g. "computer" and its Spanish translation, locale="es" translation, would be "computadora".

If the website is currently set to English, how could still access that specific string but translated to Spanish without changing the global locale for the whole website?

Something like = gettext ('computer', language='es')?

Upvotes: 1

Views: 353

Answers (2)

Al Nikolaj
Al Nikolaj

Reputation: 315

In the end, I managed to find a solution and that was to use gettext. Specifically, gettext.translation together with the path the to messages folder and your desired locale.

path = pathlib.Path.cwd() / 'app' / 'translations'

translation = gettext.translation('messages', path, 'es', fallback=True).gettext('computer')

Upvotes: 0

TkTech
TkTech

Reputation: 4976

The easiest way is to use force_locale(<language>), which is a context manager. Any translations made within this block will use the specified language.

>>> from flask_babel import force_locale, gettext
>>> with force_locale("es"):
>>>     print(gettext('computer')) # Will print "computadora".

Upvotes: 2

Related Questions