I18n on 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 they all start with /:lang .

I am currently writing 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")) } 

So I have to write as many implicit Messages as Action . Is there a better solution for this?

+5
source share
2 answers

Passing only Lang is a 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 using action composition, define a 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 can reuse LocalizedAction as follows:

 //template @(text: String)(implicit request: controllers.LocalizedRequest) @Messages("hello") //controller def lang(lang: String) = LocalizedAction(lang){implicit request => Ok(views.html.index("play")) } 
+1
source

Finally, I solved this problem as follows.

As @Infinity points out, I defined the 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 can use LocalizedAction as follows:

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

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

 @import controllers.Actions.Implicits._ 
0
source

All Articles