我正在开发一个java play framework 2.4.x项目。
我在application.conf文件中有这段代码:
play.i18n.langs = [ "en-US", "th-TH"]
在我使用play framework 1.2.x中的以下代码之前
application.langs = us_en,th_th
我想要的是让它在Play框架2.4.x中工作,如果langs采用这种格式" us_en,th_th "。
我认为我需要有一个控制器来使其工作,但我不知道如何。感谢您的帮助!谢谢。
答案 0 :(得分:0)
在迁移的情况下,您可以编写将使用旧cookie并修复它们的代码,因此一段时间后您将删除该迁移代码。
示例是
class HomeController @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport{
lazy val langCookieName = messagesApi.langCookieName
lazy val defaultLang = "en-US"
def index = Action { request => {
// Read the cookie
val langCookie = request.cookies.get(langCookieName)
// Detect the old cookie
if(langCookie.contains("_")){
// Fix it, "us_en,th_th" => "en-us", "th-th"
val langCookieFixed = langCookie.map(_.value.replace("_", "-")).getOrElse(defaultLang)
// implicit here to put language in the context, so template take it in the current request
implicit val lang = Lang(langCookieFixed)
// Draw request and change the cookie to fixed version
Ok(views.html.index("Your new application is ready.")).withLang(lang)
}else{
Ok(views.html.index("Your new application is ready."))
}
}}
在这种情况下,您计划始终接收旧格式,最好编写动作组合:
class HomeController @Inject()(val messagesApi: MessagesApi)
extends Controller with I18nSupport with Play1Actions {
def index = Play1LanguageAction { request => {
Ok(views.html.index("Your new application is ready."))
}}
}
// Trait here is for injection of MessagesApi
trait Play1Actions {
// We need MessagesApi for getting language cookie name
def messagesApi: MessagesApi
lazy val langCookieName = messagesApi.langCookieName
lazy val defaultLang = "en-US"
// Action composition
object Play1LanguageAction extends ActionBuilder[Request] {
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
// Override request with the new, fixed acceprted languages
val play1Request = new WrappedRequest[A](request) {
// Read the cookie
val langCookie = request.cookies.get(langCookieName)
// Fix it, "us_en,th_th" => "en-us", "th-th"
val langCookieFixed = langCookie.map(_.value.replace("_", "-")).getOrElse(defaultLang)
val lang = Lang(langCookieFixed)
// Override default accepted languages
override lazy val acceptLanguages = Seq(lang)
}
// Do the next action with the owerrided request
block(play1Request)
}
}
}
您也可以重写i18n模块,因此它可以与" us_en,th_th" "本地",但它还有更多工作要做。这是最初的实现: