I’m working on a Flask project and using Flask-Babel 4.0 for multilingual support. Although I have set up everything as per the documentation and there are no errors, the translations are not working — every page just defaults to English. I have already generated the .mo files, and get_locale() seems to be fetching the correct locale based on the URL segment.
Here’s a simplified version of my setup:
# Babel configuration in Flask
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['BABEL_TRANSLATION_DIRECTORIES'] = './translations'
def get_locale():
default_language = 'en'
supported_languages = ['en', 'zh', 'es', 'fr']
segments = request.path.split('/')
if segments and segments[1] in supported_languages:
g.locale = segments[1]
return segments[1]
g.locale = default_language
return 'en'
babel = Babel(app)
babel.init_app(app, locale_selector=get_locale)
@main.route('/')
@main.route('/<lang_code>/')
def index(lang_code='en'):
# Query some data, omitted for brevity
return render_template('index.html')
And the HTML template starts like this:
<!DOCTYPE html>
<html lang="{{ get_locale() }}">
<head>
<!-- Head contents -->
</head>
<body>
{{ _('Generate') }}
</body>
</html>
What I have checked so far:
The .mo files exist in the correct directories and are seemingly correct.
The get_locale() function retrieves the correct locale from URL segments.
Despite these configurations, every page still shows content in English only. Could there be something I’m missing in either the Flask-Babel setup or the way Flask handles these configurations?
Any suggestions or insights would be greatly appreciated!
kun wang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.