问题描述
虽然GWT并不是模拟所有java的核心,但可以用作以下替代方案:
While GWT is not emulate all java's core, what can be used as alternative for:
String.format("The answer is - %d", 42)?
在GWT中向消息注入参数的优雅高效模式是什么?
What is the ellegant and efficient pattern to inject arguments to message in GWT?
推荐答案
一个优雅的解决方案是使用SafeHtml模板。您可以在界面中定义多个此类模板,如:
One elegant solution is using SafeHtml templates. You can define multiple such templates in an interface like:
public interface MyTemplates extends SafeHtmlTemplates {
@Template("The answer is - {0}")
SafeHtml answer(int value);
@Template("...")
...
}
然后使用它们:
And then use them:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);
...
Label label = new Label(TEMPLATES.answer(42));
虽然这是一个更多的工作来设置,但它有一个巨大的优势,即参数是自动的HTML转义。有关详情,请参阅
While this is a little bit more work to set up, it has the enormous advantage that arguments are automatically HTML-escaped. For more info, see https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
如果您想更进一步并将您的信息国际化,请参阅
If you want to go one step further, and internationalize your messages, then see also https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages
这篇关于GWT中String.format()的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!