Finally, I used this solution: add get_locale
function, which should be defined anyway, to Jinja2 globals, and then call it in template like any other function.
Get current locale in Jinja2
-
14-04-2022 - |
Question
On my website use Flask + Jinja2, and Flask-Babel for translation. The site has two languages (depending on the URL), and I'd want to add a link to switch between them. To do this correctly I need to get the name of the current locale, but I didn't find such function in the docs. Does it exist at all?
Solution 3
OTHER TIPS
Other answers say that you must implement the babel's get_locale()
function and that you should add it to Jinja2 globals, but they don't say how. So, what I did is:
I implemented the get_locale()
function as follows:
from flask import request, current_app
@babel.localeselector
def get_locale():
try:
return request.accept_languages.best_match(current_app.config['LANGUAGES'])
except RuntimeError: # Working outside of request context. E.g. a background task
return current_app.config['BABEL_DEFAULT_LOCALE']
Then, I added the following line at my Flask app
definition:
app.jinja_env.globals['get_locale'] = get_locale
Now you can call get_locale()
from the templates.
You are responsible to store the user's locale in your session on database. Flask-babel
will not do this for you, so you should implement get_locale
method for flask-babel
to be able to find your user's locale.
This is an example of get_locale
from flask-babel
documentation:
from flask import g, request
@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# otherwise try to guess the language from the user accept
# header the browser transmits. We support de/fr/en in this
# example. The best match wins.
return request.accept_languages.best_match(['de', 'fr', 'en'])