4

I have the function in Flask, which returns the website in english. Moreover, i want to be able to use german in the website at a button push from html. How can I change the language at a button push from english to german and from german to english? Also, is it possible to use the function get_locale only at call, not running automatically?

@babel.localeselector
def get_locale():
     return 'en'  

1 Answer 1

6

At first You need to store the address at the main app file:

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

Than You need to change to the same addess to get_locale function in main app file:

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

To access current language from template:

app.config['LANGUAGES'] =  {
    'en': 'English',
    'ge': 'German',
}
app.secret_key = "super secret key"

    @app.context_processor
    def inject_conf_var():
        return dict(AVAILABLE_LANGUAGES=app.config['LANGUAGES'], CURRENT_LANGUAGE=session.get('language', request.accept_languages.best_match(app.config['LANGUAGES'].keys())))

Here the template file:

{% 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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.