2012-05-03 104 views
6

第一個問題:如何檢索控制器中文本的翻譯?播放框架2.0 - 國際化 - 如何翻譯郵件

第二個問題:如何檢索模板中文本的翻譯?

的API說有是翻譯的消息。獲得方法:

http://www.playframework.org/documentation/api/2.0/java/play/i18n/Messages.html

但是我的應用程序不能識別這種方法。在eclipse中打開Message.class表明它有一個.apply方法,用Scala和Java編寫!

object Messages { 

    /** 
    * Translates a message. 
    * 
    * Uses `java.text.MessageFormat` internally to format the message. 
    * 
    * @param key the message key 
    * @param args the message arguments 
    * @return the formatted message or a default rendering if the key wasn’t defined 
    */ 
    def apply(key: String, args: Any*)(implicit lang: Lang): String = { 
    Play.maybeApplication.flatMap { app => 
     app.plugin[MessagesPlugin].map(_.api.translate(key, args)).getOrElse(throw new Exception("this plugin was not registered or disabled")) 
    }.getOrElse(noMatch(key, args)) 
    } 

現在日食告訴我,我可以調用這個方法是這樣的:

> String play.api.i18n.Messages.apply(String arg0, Seq<Object> arg1, 
> Lang arg2) 

但我應該爲「序列」的說法進入?

--The solution--

的問題是,我進口play.api.i18n.Messages代替play.i18n.Messages ...

已經定義了兩個消息文件(messages.de -DE和messages.en-UK),並使用下面的代碼一切正常:

控制器:

import play.i18n.Messages; 
    import play.api.i18n.Lang; 

    Lang en = new Lang("en","GB"); 
    play.i18n.Lang en_lang = new play.i18n.Lang(en); 

    Lang de = new Lang("de", "DE"); 
    play.i18n.Lang de_lang = new play.i18n.Lang(de); 

    Logger.info(Messages.get("home.title")); 
    Logger.info(Messages.get(en_lang, "home.title")); 
    Logger.info(Messages.get(de_lang, "home.title")); 

application.conf

application.langs="en-GB,de-DE" 

回答

10

獲取控制器內的翻譯:

// in messages file 
msg.key=Hello Translation 

// in you controller 
Messages.get("msg.key"); 

你甚至可以傳遞參數:

// in messages file 
msg.key=Hello {0}, here is your translation 

//in controller 
Messages.get("msg.key", User.firstName); 

從視圖中,您可以使用:Messages("msg.key")

,你甚至可以將HTML格式(只適用於當然意見):

// in messages file 
msg.key=Hello <strong>{0}</strong>, here is your translation 

// in controller 
Messages.get("msg.key", User.firstName); 

//in view 
@Html(objectInView) 

請注意以下事項: 目前,它是不可能的明確定義語言,見bug報告:https://play.lighthouseapp.com/projects/82401/tickets/174-20-i18n-add-ability-to-define-implicit-lang-for-java-api

類似的問題被問過: Access translated i18n messages from Scala templates (Play! Internationalization)

i18n error: controller and templates uses different implicit languages

+0

我的播放框架不知道Messages.get(「msg.key」)方法。它會拋出錯誤:找不到符號[symbol:method get(java.lang.String)] [location:class play.api.i18n.Messages] - 也許我在使用錯誤的播放源?其實控制檯說「玩!2.0」。也許我在創建我的應用程序時選擇了「1 - 創建簡單的Scale應用程序」而不是「2 - 創建簡單的Java應用程序」。可能這是這種行爲的原因嗎? –

+0

是的,這可能是這種情況,我正在使用Java Play應用程序,而不是scala。 – adis

+0

嗯...我想知道我選擇了「1 - 簡單的Scala應用程序」,但我會在今天晚些時候嘗試一下。我不認爲這是原因,因爲在我的應用程序中創建的所有模板文件都在.java ;-) –