1

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.

4

2 回答 2

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 %}
于 2018-07-25T05:32:21.810 回答
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>

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

于 2018-07-25T08:13:10.857 回答