参考链接:https://stackoverflow.com/questions/61120324/how-to-change-language-of-flask-babel-on-a-button-click
我的flask-babel都已经设置好了,才能进入一下的代码工作
首先,您需要将地址存储在主应用程序文件view.py中:
@app.route('/language=<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('home'))
然后在 init.py 中:
@babel.localeselector
def get_locale():
if request.args.get('language'):
session['language'] = request.args.get('language')
return session.get('language', 'en')
要从模板访问当前语言,请执行以下操作:
如果你自己有config.py文件,并在文件中已设置app.config['LANGUAGES'],在这里不用设置了
app.config['LANGUAGES'] = {
'en': 'English',
'ge': 'German',
}
app.secret_key = "super secret key"
@app.context_processor
def inject_conf_var():
return dict(AVAILABLE_LANGUAGES=app.config['LANGUAGES'], CURRENT_LANGUAGE=session.get('language', request.accept_languages.best_match(app.config['LANGUAGES'].keys())))
这里是模板文件:
{% for language in AVAILABLE_LANGUAGES.items() %}
{% if CURRENT_LANGUAGE == language[0] %}
{{ language[1] }}
{% else %}
<a href="{{ url_for('set_language', language=language[0]) }}" >{{ language[1] }}</a>
{% endif %}
{% endfor %}