I got a suggestion to look the framework FreeMarker.
FreeMarker look like Velocity. You can even find converters : Velocity -> FreeMarker.
I'll describe in this part how to create the same output but using FreeMarker.
Take a look at the generate method.
SampleFreeMarker.java
public void generate() {
try {
Configuration cfg = new Configuration();
cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
Template tpl = cfg.getTemplate("./templates/GalleryTemplateFreeMarker.ftl");
OutputStreamWriter output = new OutputStreamWriter(System.out);
Map root = new HashMap();
root.put("list", mediaFileList);
tpl.process(root, output);
} catch (Exception e) {
s_logger.error("generate", e);
}
}
Let's compare to the Velocity implementation.
SampleVelocity.java
public void generate() {
try {
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("list", mediaFileList);
Template template = Velocity.getTemplate("./templates/GalleryTemplateVelocity.vm");
BufferedWriter writer = writer = new BufferedWriter(new OutputStreamWriter(System.out));
if (template != null)
template.merge(context, writer);
/*
* flush and cleanup
*/
writer.flush();
writer.close();
} catch (Exception e) {
s_logger.error("generate", e);
}
}
The main difference is with FreeMarker you need to create a root HashMap and put the objects in it.
With Velocity you put the objects within the context.
Now see the FreeMarker template.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!-- include the required JavaScript file -->
</head>
<body>
<div align="center">
<table width="80%">
<#assign maxItembyRow = 2>
<#assign index = 0>
<#assign count = 0>
<#assign newLine = true>
<#foreach mediaFile in list>
<#if newLine>
<tr>
<#assign newLine = false>
</#if>
<td>
<a href="/${mediaFile.name}" id="player${count}">
</a>
</td>
<#if index < maxItembyRow-1>
<#assign index = index + 1>
<#else>
<#assign index = 0>
<#assign newLine = true>
</#if>
<#if newLine>
</tr>
</#if>
<#assign count = count + 1>
</#foreach>
</tr>
</table>
</div>
</body>
</html>
It's almost the same as Velocity except that the syntax change a little.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!-- include the required JavaScript file -->
</head>
<body>
<div align="center">
<table width="80%">
#set( $maxItembyRow = 2)
#set( $index = 0)
#set( $newLine = true)
#foreach( $mediaFile in $list )
#if( $newLine )
<tr>
#set( $newLine = false)
#end
#if( $index<$maxItembyRow )
<td><a href="/$mediaFile.name" id="player$velocityCount">
</a>
</td>
#set($index = $index+1)
#else
#set($index = 0)
#set( $newLine = true)
#end
#end
</tr>
</table>
</div>
</body>
</html>
What I didn't like about FreeMarker is the lack of documentation.
There had good javadoc, but something you need more than that like "real life" samples.
The source code can be downloaded here.















