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>

Map of java objects is parameter for templates. Only one bean is used in our example:
public class SimpleBean {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}

A template.vm example :
simple.name = $simple.name
We 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 = Text
Comments:

Post a Comment:
Comments are closed for this entry.
About

xzajo

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today