python-babel / flask-babel

i18n and l10n support for Flask based on Babel and pytz
https://python-babel.github.io/flask-babel/
Other
432 stars 159 forks source link

Allow loading translations for a specific locale #192

Closed amadanmath closed 1 year ago

amadanmath commented 2 years ago

So far, flask_babel supports translation to the locale selected for the request. If one needs a translation into a different locale, one would need to replicate parts of flask_babel's code. A use case for this is, for example, sending an email to a site administrator in the admininistrator's language.

from flask_babel import Domain
from babel import Locale

domain = Domain(locale=Locale.parse(admin_lang))
email_body = render_template('admin_email.html', _=domain.gettext)
amadanmath commented 2 years ago

Sorry, I sent this prematurely. I have rethought a bit and updated accordingly.

TkTech commented 1 year ago

This can be done by using force_locale, see https://github.com/python-babel/flask-babel/blob/38145eeaf1cd37fa22d95e889ec66eade02e50fd/flask_babel/__init__.py#L279-L279