2013-03-16 10 views

回答

15

一個優雅的解決方案是使用SafeHtml模板。您可以在等的接口定義多個這樣的模板:

public interface MyTemplates extends SafeHtmlTemplates { 
    @Template("The answer is - {0}") 
    SafeHtml answer(int value); 

    @Template("...") 
    ... 
} 

,然後用它們:

public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class); 

... 
Label label = new Label(TEMPLATES.answer(42)); 

雖然這是一點點的工作設置,它具有極大的優點,論據自動HTML轉義。欲瞭解更多信息,請參閱https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml

如果你想多走一步,和國際化您的消息,則還看https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages

7

你可以簡單的寫的做頭腦風暴自己format function代替。

public static String format(final String format, final String... args,String delimiter) { 
    String[] split = format.split(delimiter);//in your case "%d" as delimeter 
    final StringBuffer buffer= new StringBuffer(); 
    for (int i= 0; i< split.length - 1; i+= 1) { 
     buffer.append(split[i]); 
     buffer.append(args[i]); 
    } 
    buffer.append(split[split.length - 1]); 
    return buffer.toString(); 
} 
+0

@downvoter感謝對我的post..please利益提供,我可以提高我的comment.so回答。 – 2013-03-17 06:55:12

7

因爲大多數(如在99.999%)的消息格式是靜態的,在編譯時已知的,方式GWT接近它是在編譯時來分析它們。

您通常會使用Messages subinterface來定位消息的能力,但您有時需要SafeHtmlTemplates

1

你可以寫你自己的。

我寫了一個版本,只是字符串(%S)工作:

public static String format(final String format, final Object... args) 
{ 
    checkNotNull(format); 
    checkNotNull(args); 

    final String pattern = "%s"; 

    int start = 0, last = 0, argsIndex = 0; 
    final StringBuilder result = new StringBuilder(); 
    while ((start = format.indexOf(pattern, last)) != -1) 
    { 
     if (args.length <= argsIndex) 
     { 
      throw new IllegalArgumentException("There is more replace patterns than arguments!"); 
     } 
     result.append(format.substring(last, start)); 
     result.append(args[argsIndex++]); 

     last = start + pattern.length(); 
    } 

    if (args.length > argsIndex) 
    { 
     throw new IllegalArgumentException("There is more arguments than replace patterns!"); 
    } 

    result.append(format.substring(last)); 
    return result.toString(); 
} 
-1

我不知道GWT很多,但我工作的一個GWT項目,我需要這個。在嘗試一些替代方案的同時,我發現這是行得通的;

import java.text.MessageFormat; 



MessageFormat.format("The answer is - {0}", 42); 

我不知道該項目的開發者是否增加了一些特殊的功能來使這項工作或它默認工作。

+1

這是完全錯誤的 – NimChimpsky 2017-04-06 01:59:57

+0

不存在於JRE Emulation Library中,因此它不能用於客戶端代碼 – 2017-11-27 16:44:16

+0

這對我來說只有一次。我目前沒有在GWT項目上工作。 – sedran 2017-11-28 19:54:48

0

爲什麼不寫等的方法:

String appendAnswer(int result) { 
    return "The answer is - " + Integer.toString(result); 
} 

,因爲不管你做什麼就像在你的代碼格式是解決你的問題。

,如果你曾經面臨的問題一樣整數/字節轉換爲十六進制字符串,你應該使用:

Integer.toString(int, 16); 
相關問題