Play 2.4.x how use Messages and not MessagesApi I18N

本小妞迷上赌 提交于 2019-12-06 11:54:00

If you mix in the I18nSupport trait into your controller then you have an implicit conversion in scope which translates a RequestHeader into a Messages instance. If you look into the request2Messages method then you can see that it calls the MessagesApi.preferred(request: RequestHeader) method.

So in your case you must create a subclass of DefaultMessagesApi and override the MessagesApi.preferred method to retrieve the Lang from query string as currently implemented in your controller. Then you can bind your instance to the MessagesApi trait, so that it gets automatically injected.

To bind your instance you should create your own I18nModule similar to the default one provided by Play.

Note: For Guice Injection only because it's the default method used by Play. For compile time DI you must follow another approach.

package modules

import play.api.i18n._
import play.api.{Configuration, Environment}
import play.api.inject.Module

class I18nModule extends Module {
  def bindings(environment: Environment, configuration: Configuration) = {
    Seq(
      bind[Langs].to[DefaultLangs],
      bind[MessagesApi].to[YourMessagesApi]
    )
  }
}

Then you must disable the default Play I18nModule module and enable yours.

play.modules.disabled += "play.api.i18n.I18nModule"
play.modules.enabled += "modules.I18nModule"

Now in your template you must only pass the implicit Messages instance.

 @()(implicit messages: Messages)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!