Which is the best Wicket component for rendering arbitrary HTML?

Parag picture Parag · Jan 17, 2011 · Viewed 7.5k times · Source

I am implementing a simple markdown wiki using Apache Wicket. The wiki would typically render any arbitrary HTML based on what the user has entered.

I am a bit confused about which Wicket component would be best suited to render such arbitrary HTML.

I tried the Label component but it does not render lists properly, neither does the MultilineLabel (which puts breaks instead of the regular list HTML).

Thanks for any help.

UPDATE: The Label component works perfectly. It was my mistake that I was not able to get it to work earlier. It was a combination of some bad stylesheets and late night coding. Thanks for the helpfull answers. As suggested, I am also going to check out some WYSIWYG editors, which actually might work out better than markdown. Visural Wicket seems especially promising.

Answer

tetsuo picture tetsuo · Jan 17, 2011

If what you want to render is not big, or is already represented as a String, Label will work well, just call label.setEscapeModelStrings(false); to ensure it prints the string as is.

But, if your HTML content is generated dynamically, or read from an InputStream/Reader, and you don't want to keep it in memory, you could use WebComponent directly, and override the method onComponentTagBody(). This way, you write directly to the response, instead of filling a in-memory buffer, transform it to a String, and then write to the response (which happens if you use Label).

Sample code, for both cases:

HomePage.java

public class HomePage extends WebPage {

    public HomePage() {

        add(new Label("label", "<ul><li>test</li><li>test</li><li>test</li><li>test</li><li>test</li></ul>")
            .setEscapeModelStrings(false));

        add(new WebComponent("html") {
            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                Response response = getRequestCycle().getResponse();
                response.write("<ul>");
                for (int i = 0; i < 5; i++)
                    response.write("<li>test</li>");
                response.write("</ul>");
            }
        });
    }
}

HomePage.html

<html xmlns:wicket="http://wicket.apache.org">
<body>
  <h2>Label</h2>
  <div wicket:id="label"></div>
  <h2>WebComponent</h2>
  <div wicket:id="html"></div>
</body>
</html>