1

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')?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Al Nikolaj
  • 305
  • 4
  • 13

3 Answers3

2

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".
TkTech
  • 4,729
  • 1
  • 24
  • 32
0

Have you tried using the tutorial by miguel? Flask Mega Tutorial

DhaniPro
  • 59
  • 1
  • 8
0

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')
Al Nikolaj
  • 305
  • 4
  • 13