GWT: Putting raw HTML inside a Label

后端 未结 5 2691
情深已故
情深已故 2021-02-20 08:26

Is there a way to put raw HTML inside of a Label widget with GWT? The constructor and setText() methods automatically escape the text for HTML (so

5条回答
  •  鱼传尺愫
    2021-02-20 08:44

    Sorry, I'm going to answer my own question because I found what I was looking for.

    The SafeHtmlBuilder class is perfect for this. You tell it what strings you want to escape and what strings you do not want to escape. It works like StringBuilder because you call append methods:

    String matched = "two";
    List values = Arrays.asList("one", "two", "three ");
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    for (String v : values){
      if (v.equals(matched)){
        builder.appendHtmlConstant("");
        builder.appendEscaped(v);
        builder.appendHtmlConstant("");
      } else {
        builder.appendEscaped(v);
      }
      builder.appendEscaped(", ");
    }
    HTML widget = new HTML();
    widget.setHTML(builder.toSafeHtml());
    //div contains the following HTML: "one, two, three <escape-me>, "
    

    Note that the appendHtmlConstant method expects a complete tag. So if you want to add attributes to the tag whose values change during runtime, it won't work. For example, this won't work (it throws an IllegalArgumentException):

    String url = //...
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    builder.appendHtmlConstant("link");
    

提交回复
热议问题