I'm configuring flask-babel to translate an html page from English as base language to Portuguese as translated language. However, no changes at get_locale() reflected in a different language.
These are my current relevant codes:
app.py:
from flask import Flask, render_template
from flask_babel import Babel
from flask_babel import gettext as _
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'pt'
babel = Babel(app)
babel.init_app(app)
def get_locale():
return 'en'
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
html:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>{{ _('Word') }}</h1>
</body>
</html>
Switching manually app.config['BABEL_DEFAULT_LOCALE'] = 'pt'
seems to show equivalent translated word as written in '.po' file and then compiled, and switching ['BABEL_DEFAULT_LOCALE']
to 'en' and get_locale()
to 'pt' seems to show the untranslated word again. In other words, I think my 'messages.mo' file is working as intended. It's as if the get_locale() function is getting ignored.
I'm using flask 2.2.2 and flask-babel 3.0.0, thus, I didn't insert @babel.localeselector
as it seems it's not needed (and returns unrecognized decorator when inserted).
Thanks in advance
----- ANSWER -----
Using babel.init_app(app, locale_selector=get_locale)
didn't work for the first few times, until I wrote my code in the following order: babel initialization, then get_locale() function, then init_app.
from flask import Flask, render_template
from flask_babel import Babel
from flask_babel import gettext as _
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)
def get_locale():
return 'en'
babel.init_app(app, locale_selector=get_locale)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
CodePudding user response:
Did you check documentation?
You have to set locale_selector
to be able use own function:
...
def get_locale():
return 'en'
babel = Babel(app)
babel.init_app(app, locale_selector=get_locale)
...