简体   繁体   中英

I18n in Play Framework 2.4.0

Here is my routes file:

GET /:lang      controller.Application.index(lang: String)
GET /:lang/news controller.Application.news(lang: String)

Note that all of them start with /:lang .

Currently, I write Application.scala as

def index(lang: String) = Action {
  implicit val messages: Messages = play.api.i18n.Messages.Implicits.applicationMessages(
    Lang(lang), play.api.Play.current)
  Ok(views.html.index("title"))
}

In this way, I have to write as many implicit Messages as Action . Is there any better solution for this?

Passing just Lang is simpler option:

def lang(lang: String) = Action {
    Ok(views.html.index("play")(Lang(lang)))
}

//template
@(text: String)(implicit lang: play.api.i18n.Lang)
@Messages("hello")

You can reuse some code by using action composition, define wrapped request and action:

case class LocalizedRequest(val lang: Lang, request: Request[AnyContent]) extends WrappedRequest(request)

def LocalizedAction(lang: String)(f: LocalizedRequest => Result) = {
    Action{ request =>
      f(LocalizedRequest(Lang(lang), request))
    }
}

Now you are able to reuse LocalizedAction like this:

//template
@(text: String)(implicit request: controllers.LocalizedRequest)
@Messages("hello")

//controller
def lang(lang: String) = LocalizedAction(lang){implicit request =>
    Ok(views.html.index("play"))
}

Finally, I solved this problem in the following way.

As @Infinity suggests, I defined wrapped request and action as:

case class LocalizedRequest(messages: Messages,
                            request: Request[AnyContent])
  extends WrappedRequest(request)


object Actions {
  def LocalizedAction(lang: String)(f: LocalizedRequest => Result) = {
    Action { request =>
      f(LocalizedRequest(applicationMessages(Lang(lang), current), request))
    }
  }

  object Implicits {
    implicit def localizedRequest2Messages(implicit request: LocalizedRequest): Messages = request.messages
  }
}

Now I'm able to use LocalizedAction like this:

def lang(lang: String) = LocalizedAction(lang) { implicit request =>
    Ok(views.html.index("play"))
}

However, in order to omit the implicit parameter of Messages , which should be a play.api.i18n.Messages , I added a line to my template as:

@import controllers.Actions.Implicits._

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM