Reputation: 315
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
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
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