views:

79

answers:

3

I'm always looking for a modern Java library that makes creating valid (X)HTML snippets easy.

Yes you could use a templating language but there are times when you do not want to do this because Java has some advantages over insert your favorite templating language.

I have seen lots of in-house HTML builders in many projects but there is no Commons-HTML Builder that I can find.

Does anyone know of one?

It would be ideal if it took advantage of the Java 5/6/7 type system (generics) and support Fluent Style. Or something like fluent style ie JQuery style chaining, or a state machine used in mocking libraries like JMock (pedantically speaking a Monad).

A rough builder example might be:

new Html().title("stuff").body().in().div().in().h1("Hello World").hr();

Another example: http://codemonkeyism.com/the-best-markup-builder-i-could-build-in-java/

I ended up writing my own: Java Anti-template Language (JATL)

+2  A: 

Have you tried the Jakarta Element Construction Set (ECS) project?

It is not really a fluent API - reminds me more of StringBuilder than Mockito... But functionally I think it is what you're after.

serg10
This is definitely a step in the right direction (+1)
seanizer
I think we have a winner. What a horrible non-friendly SEO project name :)Your right its probably not really fluent as it would involve a state machine. If anything its actually more like a Monad. Think JQuery.
Adam Gent
It still seems clunky to me and doesn't support XHTML.
Adam Gent
+1  A: 

Your best bet is probably to use an XML library and render the output as HTML.

I.E. Dom4J defines a HtmlWriter class for HTML-specific XML output.

But you'd still have to create your own api on top of it to actually create the document.

seanizer
The annoying probablem with Dom4J its lack of support of generics.ie node.elements() returns a List<?> not List<Element>But is my favorite XML library for Java
Adam Gent
A: 

I ended up writing my own library called Java Anti-template Language (JATL)

Adam Gent