Fynn
Fynn

Reputation: 4873

Play! framework's .withLang(...) not taking effect immediately

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:

  1. call /somePage1: served in default language
  2. call /somePage2?lang=en: still served in default language
  3. call /somePage3: served in english

Why is the language change not taking effect immediately?

Upvotes: 2

Views: 456

Answers (1)

Fynn
Fynn

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

Related Questions