Salviati
Salviati

Reputation: 788

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

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.

Upvotes: 2

Views: 1579

Answers (2)

Sushant
Sushant

Reputation: 3669

Probably something like this might help you.

Set a route that handles language change and stores the selected language on the session:

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

You have get_locale() set-up that returns the selected language but you needs to be able to access it from the template. So

@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())))

Finally, in the template, choose the the language you want:

{% 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 %}

Upvotes: 1

Salviati
Salviati

Reputation: 788

Probably the worst way to do it, but it works.

First I had to change index to accept GET method:

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

Then add in the HTML file a form method

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

Will not accept this answer because it does not look right, must be a better way

Upvotes: 0

Related Questions