GWT: Putting raw HTML inside a Label

后端 未结 5 2758
情深已故
情深已故 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:36

    Either create a label and set it to bold:

    Label label = new Label("text");
    label.getElement().getStyle().setFontWeight(FontWeight.BOLD);
    

    Or you can create a SpanElement and set its innerHtml.

    0 讨论(0)
  • 2021-02-20 08:43

    I think you should use SpanElement where you don't want the html to be escaped and label where you want then to be escaped and put them on a vertical panel so that they would appear as a single line of text.

    0 讨论(0)
  • 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<String> values = Arrays.asList("one", "two", "three <escape-me>");
    SafeHtmlBuilder builder = new SafeHtmlBuilder();
    for (String v : values){
      if (v.equals(matched)){
        builder.appendHtmlConstant("<b>");
        builder.appendEscaped(v);
        builder.appendHtmlConstant("</b>");
      } else {
        builder.appendEscaped(v);
      }
      builder.appendEscaped(", ");
    }
    HTML widget = new HTML();
    widget.setHTML(builder.toSafeHtml());
    //div contains the following HTML: "one, <b>two</b>, three &lt;escape-me&gt;, "
    

    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("<a href=\""); //throws IllegalArgumentException
    builder.appendEscaped(url);
    builder.appendHtmlConstant("\">link</a>");
    
    0 讨论(0)
  • 2021-02-20 08:46

    Use the HTML class (Or more likely: The InlineHTML class instead of the Label class. InlineHTML works like label, except that you can give it html.

    And just a security warning: if part of the input to your InlineHTML object is input by the user, remember to strip html out of that part, so users can't insert their own scripts into your code.

    0 讨论(0)
  • 2021-02-20 08:47

    Here's example to put a space in a widget, e.g. Label:

    public void setTextNbsp( final Widget w ) { 
        w.getElement().setInnerHTML( "&nbsp;" );
    }
    

    Other HTML entities could be used as well. Take care with this not to open security holes. SafeHtml, etc. might need consideration if doing something more dynamic.

    0 讨论(0)
提交回复
热议问题