Play framework 2.3 change template language without further request
The usual way to change the language is to do a redirect with
.withLang(Lang(newLangCode))
but how best to change the current language without additional redirection, I have the following construction. I am trying to use the language from a user entry or from cookies or request headers if the user does not have a language.
def index(userId:Int) = Action {
val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
Ok(views.html.index(...)).withLang(userLang)
}
But this approach doesn't work: view.html.index (...) is called with the old implicit lang and "withLang" only sets the cookie for the new request.
I only know of one solution: call template function with an explicit lang parameter.
def index(userId:Int) = Action {
implicit request =>
val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
Ok(views.html.index(...)(request,userLang)).withLang(userLang)
}
But could there be a more canonical way to switch languages?
source to share
You must declare the value userLang
as implicit. This way, your value userLang
will be automatically matched for your template argument @(...)(implicit lang: Lang)
.
def index(userId:Int) = Action { request =>
implicit val userLang = getUser(userId).getLang.getOrElse(implicitly[Lang])
Ok(views.html.index(...)).withLang(userLang)
}
You also need to remove the implicit modifier from the request argument, because there Controller
is an implicit conversion from the implicit request for lang in, and the compiler will complain about ambiguous implicit parameters.
source to share