Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
DANG Fan Avatar asked Nov 10 '22 15:11

DANG Fan


1 Answers

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"))
}
like image 90
Infinity Avatar answered Nov 15 '22 12:11

Infinity