這是我碰到的解決方案:
首先你要定義將處理語言的變化,並且將所選擇的語言存儲在會話路由:
@app.route('/language/<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('index'))
其次,你必須修改一點點的代碼,你必須得從會話中選擇的語言:
@babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = session['language']
except KeyError:
language = None
if language is not None:
return language
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
您也可以訪問從模板中CURRENT_LANGUAGE,S啊,你可以把它注射:
@app.context_processor
def inject_conf_var():
return dict(
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 %}
希望這有助於!