Search code examples
javahtmltemplate-engine

Better Html Builder in java


I want to get below output.

<html>
<head>
</head>
<body>
<table>
<tbody>
<thead>
Blah Blah table Header--Constant Part
</thead>
<tr>
some text-constant part
</tr>
<!---Main Customization Part-->
for(i=0;i<some value;i++)
{
<tr>
    for(j=0;j<another value;j++)
    {
        if(some condition)
        {
            <td class=another varibale>some text</td>
        }
        else
        {
            <td class=yet another varibale>some text</td>
        }
    }
</tr>
}
</body>
</html>

As you can see its a mixture of html and it will generate the rest from java logic. Now here is my question-how can I implement in standalone java(i.e not jsp).I know I can write this to a normal file.But somehow I feel thats a ugly solution.Is there any way to get it done in some nicer way? Basically I am looking for a good HTML builder for java. Already checked-Freemarker. Also I am open to implement in any language,As java is my favourite language,so I am prefering it.


Solution

  • Gagawa "allows developers to easily and dynamically build well-formed HTML in web or non-web applications".

    It requires the use of one jar and the source code is freely available to peruse.

    An example...

    Div div = new Div();
    div.setId("mydiv").setCSSClass("myclass");
    
    A link = new A();
    link.setHref("http://www.example.com").setTarget("_blank");
    
    div.appendChild( link );
    
    Img image = new Img( "some alt", "some-image.png" );
    image.setCSSClass( "frame" ).setId( "myimageid" );
    link.appendChild( image );
    
    System.out.print( div.write() );
    

    This produces the following HTML:

    <div id="mydiv" class="myclass">
      <a href="http://www.example.com" target="_blank">
       <img alt="some alt" src="some-image.png" class="frame" id="myimageid">
      </a>
    </div>