How do I add a link to change and keep a new language using babel and flask?

时间:2018-07-25 05:14:02

标签: python flask babel

I have setup Babel correctly and the translation work as intended. What I am stuck with is to be able to switch languages using a link and than keep that setting active even if the user click on any other links on the web page.

This is what my setup looks like:

app = Flask(__name__)
app.config["BABEL_DEFAULT_LOCALE"] = "en"
babel = Babel(app)

@babel.localeselector
def get_locale():
    if request.args.get("lang"):
        session["lang"] = request.args.get("lang")
    return session.get("lang", "en")

This works as expected and a new user is greeted with the 'en' version of the web page. I am able to manually switch by typing '/?lang=sv' or '/?lang=en' after the address in the search field, but how do I do it with a link?

This is probably basic but I do not understand how to do it based on their documentation. Also this is the first time for me so it feels like I have taken water over my head.

2 个答案:

答案 0 :(得分:1)

可能类似的东西可能会对您有所帮助。

设置处理语言更改并将其存储在会话中的路由:

@app.route('/language/<language>')
def set_language(language=None):
    session['language'] = language
    return redirect(url_for('index'))

您有get_locale()设置可以返回所选语言,但是您需要能够从模板访问它。所以

@app.context_processor
def inject_conf_var():
    return dict(CURRENT_LANGUAGE=session.get(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 %}

答案 1 :(得分:0)

这可能是最糟糕的方法,但是它可行。

首先我必须更改索引以接受GET方法:

@app.route("/", methods=['GET'])
def index():
    return render_template("index.html", me=me)

然后在HTML文件中添加表单方法

<form method="GET">
  <input type="submit" name="lang" value="sv">
  <input type="submit" name="lang" value="en">
</form>

将不会接受此答案,因为它看起来不正确,必须是更好的方法