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
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");