Hello Stackoverflow community!
I have i18n working in my Play 2.4 application, so that's a good start.
What I want to do now is to override the implicit Lang
sent to a template. For example, if the IP address is located in Sweden, I want to set the implicit Lang
to Swedish regardless of what preferred language is set in the browser. How to do this?
This is my code:
My Application.scala
controller:
package controllers
import javax.inject.Inject
import play.api.i18n.{I18nSupport, Lang, MessagesApi}
import play.api.mvc._
class Application @Inject() (val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
if (isIpAddressLocatedInSweden) {
implicit val langFromIp = Lang.apply("sv")
Logger.info("Language set to Swedish")
}
Ok(views.html.index())
}
private def isIpAddressLocatedInSweden: Boolean = {
[...]
}
}
My index.scala.html
view:
@()(implicit messages: Messages, lang: Lang)
@main("Page Title") {
<span>@lang.toString()</span>
<h1>@Messages("home.title")</h1>
}
Unfortunately, the result is:
<span>
element contains the preferred browser language: "Lang(en,)"<h1>
element contains the value I've written in messages.en
Thanks for any help!
This is the cleanest way I got it to work:
Code of my Application.scala
controller:
class Application @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
val lang = if (isIpAddressLocatedInSweden) {
Lang.apply("sv")
} else {
Lang.preferred(request.acceptLanguages)
}
Ok(views.html.index()).withLang(lang)
}
private def isIpAddressLocatedInSweden: Boolean = {
[...]
}
}
The code of the index.scala.html
view is unchanged.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments