Reputation: 4873
I want to allow the user of my web application to change the current language (for i18n purposes). This is done by appending the language code to the URL as a HTTP GET parameter (e.g. /somePage?lang=en
). The language code is then resolved in the correspionding controller method and set via .withLang(lang)
.
I am using action composition to provide this functionality and avoid boilerplate code:
def withLang(f: => Request[AnyContent] => Result) = Action { implicit request =>
request.getQueryString("lang").flatMap(Lang.get(_)) match {
case Some(lang) => f(request).withLang(lang)
case None => f(request)
}
}
The composition can then be used as follows:
def somePage = withLang { implicit request =>
//do some stuff
Ok(views.html.somePage())
}
This solution works fine. If I call /somePage?lang=en
, the language of the web application is permanently switched to english. However, this only applies to subsequent pages. The current page is still served in the old language:
/somePage1
: served in default language/somePage2?lang=en
: still served in default language/somePage3
: served in englishWhy is the language change not taking effect immediately?
Upvotes: 2
Views: 456
Reputation: 4873
I just solved it by using a Redirect
instead of rendering the page directly:
def withLang(f: => Request[AnyContent] => Result) = Action { implicit request =>
val referrer = request.headers.get(REFERER).getOrElse("/")
request.getQueryString("lang").flatMap(Lang.get(_)) match {
case Some(lang) => Redirect(referrer).withLang(lang)
case None => f(request)
}
}
Upvotes: 4