在我的网站上使用Flask + Jinja2和Flask-Babel进行翻译。该站点有两种语言(取决于URL),我想添加一个链接来在它们之间切换。为了正确地做到这一点,我需要获取当前语言环境的名称,但我在文档中没有找到这样的函数。它真的存在吗?
发布于 2013-05-05 21:48:40
最后,我使用了这个解决方案:将get_locale函数添加到Jinja2全局变量中,然后像其他函数一样在模板中调用它。
发布于 2019-09-12 03:49:24
其他人回答说,你必须实现巴别塔的get_locale()函数,你应该把它添加到Jinja2全局变量中,但他们没有说如何实现。所以,我所做的是:
我按如下方式实现了get_locale()函数:
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']然后,我在我的Flask app定义中添加了以下行:
app.jinja_env.globals['get_locale'] = get_locale现在您可以从模板中调用get_locale()。
发布于 2013-05-05 19:55:02
您负责将用户的区域设置存储在数据库中的会话中。Flask-babel不会为您做这件事,所以您应该为flask-babel实现get_locale方法,以便能够找到您的用户的语言环境。
以下是flask-babel文档中的get_locale示例:
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'])https://stackoverflow.com/questions/16384192
复制相似问题