Tho*_*mel 6 internationalization playframework-2.0
第一个问题:如何检索控制器中文本的翻译?
第二个问题:如何检索模板中文本的翻译?
api说有一个.get方法可以翻译一条消息:
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))
}
Run Code Online (Sandbox Code Playgroud)
现在eclipse告诉我,我可以像这样调用这个方法:
> String play.api.i18n.Messages.apply(String arg0, Seq<Object> arg1,
> Lang arg2)
Run Code Online (Sandbox Code Playgroud)
但是我应该输入什么作为"Seq"参数呢?
- 解决方案 -
问题是我导入了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"));
Run Code Online (Sandbox Code Playgroud)
application.conf
application.langs="en-GB,de-DE"
Run Code Online (Sandbox Code Playgroud)
adi*_*dis 10
获取控制器内的翻译:
// in messages file
msg.key=Hello Translation
// in you controller
Messages.get("msg.key");
Run Code Online (Sandbox Code Playgroud)
你甚至可以传递参数:
// in messages file
msg.key=Hello {0}, here is your translation
//in controller
Messages.get("msg.key", User.firstName);
Run Code Online (Sandbox Code Playgroud)
从视图中您可以使用: 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)
Run Code Online (Sandbox Code Playgroud)
请注意以下内容: 目前无法明确定义语言,请参阅错误报告:https://play.lighthouseapp.com/projects/82401/tickets/174-20-i18n-add-ability-to-define-隐琅换Java的API
之前曾问过类似的问题: 从Scala模板访问翻译的i18n消息(Play!Internationalization)