I have an application in which I have managed to use translations for romanian and english. I want to press the button "english" and get the website translated in english and when pressing "romanian" the website should translate to romanian.
I have managed to do this so far, but whenever I click on whether english or romanian, the website goes to the home page. How can I redirect the flask page to the current page, for example contact page? Now, if I am on the contact page and press "english", the website gets translated in english but redirects me to home page. I am using Flask Babel for translation.
For the button I have the following code in index.html
:
<a class="dropdown-item" href="/language/en">English</a>
<a class="dropdown-item" href="/language/ro">Romanian</a>
And the code from app.py
for the translations is:
LANGUAGES = {
'en': 'English',
'ro': 'Romanian'
}
@app.route('/')
def home():
return render_template("index.html")
@app.route('/language/<language>')
def set_language(language=None):
session['language'] = language
return redirect(url_for('home'))
@babel.localeselector
def get_locale():
try:
language = session['language']
except KeyError:
language = None
if language is not None:
return language
return request.accept_languages.best_match(LANGUAGES.keys())
@app.context_processor
def inject_conf_var():
return dict(
AVAILABLE_LANGUAGES=LANGUAGES,
CURRENT_LANGUAGE=session.get('language', request.accept_languages.best_match(LANGUAGES.keys())))
This answer was posted as an edit to the question How to use translation in Flask? by the OP moro_922 under CC BY-SA 4.0.