the blog for developers

The best Markup Builder I could build in Java

Using Groovy MarkupBuilders spoiled me for other ways to create HTML pages from code. Others think the same. But in some organizations you have to use Java and can’t use Groovy – at least when you can’t sneak it in.

So I tinkered around in Java to see what’s the best MarkupBuilder I can write with Java. Using DSLs and Fluent Interfaces (times(5).loop), I came up with a nice solution. It’s not Groovy, but it works.

   Page page = page(
      html(
        body(
          // A comment
          h1("Name games"),
          p("Hello ${coolName}, and hello", "id:${id}"),
          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
            }),
          loop("[${number}] ", "number", 1, 2, 3),
          text("..."),
          box("Warning private!"),
          p("Are you dynamic?"),
          // Some dynamic content
          new Action() {
            protected String with(Context context) {
              return "I'm dynamic, " + context.get("name") + ".";
            }
          }
        )
      )
    );

There are some tricks to make it better than most such Markup Builders in Java. I tried to use ideas from building DSLs in Java. Those are using static imports and varargs. The body, html and other elements are static imports from a MarkupBuilder class.

  public static Element body(String body) {
    return new Element("body", body);
  }
  public static Element body(Element... elements) {
    return new Element("body", elements);
  }
  ...

The varargs helps with adding a variable number of childs to an element:

h1(
   p("One"),
   p("Two"),
   p("Three")
);

Another problem is how to put object values into the generated markup. String concatenation leads to noisy code

  "Hello " + name + "!"

so I decided to use a expression language where the Java unified expression language comes to mind. There is an open source version available called JUEL. Now I can use

  "Hello ${name}!"

Attributes are also treated as expressions and seperated by commas, their names and values seperated with a colon.

   p("Hello ${coolName}, and hello", "id:${id}, class:list"),

Loop and Action classes allow for dynamic content.

          
          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
           }),

I’ve used the template design pattern for this, again with expressions, in a way Spring provides JDBC templates. Another nice idea is with static methods it’s also easy to develop custom, semantic tags, so the developer doesn’t need to know or see the actual HTML markup which is created. For example I used a box “tag” which translates to

public static Element box(String text) {
  return div(
                 p(text)
           );
}

Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like. When they add syntactic sugar to create maps I can drop the “name:value, name:${value}” style for attributes and move to [ "name" : value, "name": value ] instead, which doesn’t need the EL to work. With some small things to add the MarkupBuilder can be used for JSON or XML.

I’m interested and open to all techniques and ideas to improve the markup builder.

Thanks for listening.

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

Discuss on Hacker News Vote on HN