2017-03-14 108 views
0

我正在開發一個java play framework 2.4.x項目。如何修改play play framework 2.4.x中的java play i18n lang?

我在application.conf文件驗證碼:

play.i18n.langs = [ "en-US", "th-TH"] 

之前我在玩框架1.2.x的使用下面的代碼

application.langs = us_en,th_th 

我要的是使它工作在播放框架2.4.x中,如果langs的格式爲「us_en,th_th」。

我想我需要一個控制器來使它工作,但我不知道如何去做。感謝你的幫助!謝謝。

回答

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) 
    } 
    } 
} 

您也可以重寫國際化模塊,所以它會「本土化」與「us_en,th_th」合作,但它的工作量更大。這裏是原始執行:

https://github.com/playframework/playframework/tree/2.5.x/framework/src/play/src/main/scala/play/api/i18n

相關問題