Thursday September 07, 2006 Using velocity templates in NBM projects
Many people asked me how to use velocity template in their NetBeans module projects. So there is short example. Velocity libraries are wrapped to org-apache-velocity.nbm NetBeans module.
First time you need to install the module to NetBeans platform. Now we can start to write Velocity module. Add org-apache-velocity on classpath of module. Example class with generating code is below:
public class SimpleTemplate {
/** Write generated code to target document
*/
public static void apply(Writer t,String vmTemplate,Map beans) {
try {
VelocityContext context = VTResourceLoader.getContext();
for (Iterator bIt = beans.keySet().iterator() ; bIt.hasNext() ;) {
String name = (String)bIt.next();
Object bean = beans.get(name);
context.put(name, bean);
}
Template template = Velocity.getTemplate(vmTemplate);
if (t == null) {
throw new IllegalStateException(" no target defined ");
}
template.merge(context, t);
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.SEVERE,"Exception during generating templates",e);
}
}
}
The velocity template is present in velocity/templates folder of layer.xml :
<folder name="velocity">
<folder name="templates">
<file name="template.vm" url="Simple.vm"/>
</folder>
</folder>
public class SimpleBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
template.vm example :
simple.name = $simple.nameWe can write action with body:
public void performAction() {
// TODO implement action body
InputOutput io = IOProvider.getDefault().getIO("template test",true);
Map map = new HashMap();
SimpleBean sb = new SimpleBean();
sb.setName("Text");
map.put("simple",sb);
SimpleTemplate.apply(io.getOut(),"template.vm",map);
}
It prints to output window transformed template:
simple.name = TextPosted by xzajo ( Sep 07 2006, 03:56:47 PM CEST ) Permalink Comments [6]