问题
I've done a little bit different form the internationalization guide, at the play I18N guide
I forced the result to the language in the query string, it works, but it needs to be done in the "correct way". It's a good form to keep the work and look for better approach later:
NOTE: I USED THE "MessagesApi" to make it happen.
please see the code below:
package controllers
import play.api._
import play.api.mvc._
import play.api.i18n.I18nSupport
import play.api.i18n.Messages.Implicits._
import play.api.i18n.MessagesApi
import javax.inject.Inject
import play.api.i18n.Lang
import play.api.i18n._
class Application @Inject() ( val messagesApi: MessagesApi) extends Controller with I18nSupport {
def index = Action { implicit request =>
request.getQueryString("lang") match{
case Some(lang) => messagesApi.setLang(Ok(views.html.index()(messagesApi,Lang(lang))),Lang(lang))
case None => messagesApi.setLang(Ok(views.html.index()(messagesApi,Lang("en"))),Lang("en"))
}
}}
index.scala.html
@()(implicit message: MessagesApi ,l: Lang)
<li><a href="./?lang=en"><img src="@routes.Assets.versioned("images/BR.png")" /></a></li>
<li><a href="./?lang=en"><img src="@routes.Assets.versioned("images/US.gif")" /></a></li>
<header>
<h1>@message("intro")</h1>
</header>
<p>@Html(message("description"))</p>
conf/application.conf
play.i18n.langs = [ "en", "pt","fr" ]
回答1:
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)
来源:https://stackoverflow.com/questions/32382289/play-2-4-x-how-use-messages-and-not-messagesapi-i18n