在遷移的情況下,您可以編寫與舊的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)
}
}
}
您也可以重寫國際化模塊,所以它會「本土化」與「us_en,th_th」合作,但它的工作量更大。這裏是原始執行:
https://github.com/playframework/playframework/tree/2.5.x/framework/src/play/src/main/scala/play/api/i18n