Language selector in Play 2.4 & Scala 2.11.6

715 views Asked by At

I'm trying to implement this simple page with a language selector and a localized message:


|...en...|▼|

A message in english


Ideally when the user changes the language the page should reload with an updated message and a different selected language


|....fr....|▼|

Un message en français


but I can't get this to work: the page stays the same and the only thing that changes is the PLAY_LANG cookie.

controller

package controllers

import javax.inject.Inject
import play.api.mvc._
import play.api.i18n._
import play.api.data._
import play.api.data.Forms._

class Test @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
  def index = Action { implicit request =>
    Ok(views.html.test())
  }
  def changeLanguage() = Action { implicit request =>
    val referrer = request.headers.get(REFERER).getOrElse("/")
    val form = Form("language" -> nonEmptyText)
    form.bindFromRequest.fold(
      errors => BadRequest(referrer),
      language => Redirect(referrer).withLang(Lang(language))
    )
  }
}

template

@()(implicit messages: Messages, lang: Lang)
@helper.form(action = routes.Test.changeLanguage()) {
    <select name="language" style="width: auto;"> onchange="this.form.submit()">
        @play.api.i18n.Lang.availables(play.api.Play.current).map { l =>
            <option value="@l.code" @(if(lang.code.startsWith(l.code)) "selected")>@l.code</option>
        }
    </select>
    <h1>@Messages("test.message")</h1>
}

Any help would be appreciated.

2

There are 2 answers

0
ChrisEx On BEST ANSWER

The culprit was an unintentional extra ">" symbol inside the template:

                                            v
<select name="language" style="width: auto;"> onchange="this.form.submit()">
                                            ^

This typo didn't generate any error but prevented the server.side code from being executed.

I should have noticed that the cookie didn't get changed anymore (it did initially when the language-changing code was not working and when I finally got it to work I must have introduced the typo inside the template).

3
Sergey On

request in action should be implicit.

def index = Action {
implicit request =>