TL;DR:
In Flask - I want to have a language selection drop-down in my navigation bar in my base template - so that language selection is possible from each page. I want it so that when the user clicks an option in the drop-down, they stay on the same page but have it refreshed with the new translations (with new parameters passed to the view function and the template reloaded).
I only know how to redirect to:
- request.url (which would be the url for the button, which I don't want, I want the page that the user clicked from).
- request.referrer (which is the actual previous url, but since I changed the language the url has changed too, so I don't want the same url, I want the same route.
Since the user can click from various pages I can't just say "url_for(a certain route)" because that would hard code it to one route and I want this to depend on where the user was when they clicked. Otherwise using url_for with my locale parameter works as intended. I just can't use it to "refresh dynamically" so to say.
So is there a way that I can do something similar to request.referrer, but with the referring view function - not the referring url? Sort of like:
redirect(request.referring_route(locale=newlocale))
Some examples of my routes:
# Index page
@user_blueprint.route("/<locale>", methods=["GET"])
def index(locale):
return render_template("index.html")
# Some word info page with a word parameter
@user_blueprint.route("/<locale>/word/<word_id>", methods=["GET"], defaults={"locale": "en"})
@user_blueprint.route("/<locale>/ord/<word_id>", methods=["GET"], defaults={"locale": "da"})
def wordinfo(word_id, locale):
myword = words.get(word_id)
return render_template("wordinfo.html", myword=myword)
# This could be my route for changing language
@user_blueprint.route("/<locale>/refresh_language", methods=["GET", "POST"])
def refresh_language(locale):
if locale in accepted_languages:
session["locale"] = locale
return redirect(referring_route_with_same_parameters_but_new_locale(locale=locale))
I tried using request.referrer and have a decorator to force a redirect to the url that matches the session, but that also means forcing the user to always see the language they have in session and then they wouldn't be able to receive a link to a different language version. And that bothers me. I want the session language/preferred language to change when the user enters a complete, valid url for a different language version of a page.