Knowledge Walls
John Peter
Pune, Maharashtra, India
How to include vm file into another vm file in java apache velocity with Example
10621 Views
UserInfo
public class UserInfo{
    private int rollno;
    private String username;
    private int age;
    private String sex;
    
    public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}
NestedVMFileExample
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class NestedVMFileExample {
    public static void main(String args[]){
        VelocityEngine ve = new VelocityEngine();
        ve.init();
         
        Template t = ve.getTemplate("velocitytemplate.vm");
         
        VelocityContext vc = new VelocityContext();
        List<UserInfo> userInfoList = new ArrayList<UserInfo>();
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1001);
            userinfo.setUsername("Parthasarathy");
            userinfo.setAge(22);
            userinfo.setSex("male");
            
            userInfoList.add(userinfo);
        }
        {
            UserInfo userinfo = new UserInfo();
            userinfo.setRollno(1002);
            userinfo.setUsername("Lakshanya");
            userinfo.setAge(12);
            userinfo.setSex("female");
            
            userInfoList.add(userinfo);
        }
        
        vc.put("user_info_list", userInfoList);
        
        StringWriter sw = new StringWriter();
        t.merge(vc, sw);
         
        System.out.println(sw);
    }
}
Userinfoshower.vm 
RollNo: $userinfo.getRollno()
Username: $userinfo.getUsername()
Age: $userinfo.getAge()
Sex: $userinfo.getSex()
Velocitytemplate.vm 
User Details
------------
#foreach ($userinfo in $user_info_list)
#parse ("userinfoshower.vm")
#end
Output 
User Details
------------
RollNo: 1001
Username: Parthasarathy
Age: 22
Sex: male

RollNo: 1002
Username: Lakshanya
Age: 12
Sex: female
Best Lessons of "Java Apache Velocity Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details