tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Template Engines > Freemarker > Object List Iteration

Object List Iteration 

FreeMarker is a java based template engine for complex template processing. This requires the library freemarker-2.3.16.jar to be in classpath. The following example shows iterating object lists.

File Name  :  
/FREEMARKER001/config/objlist.ftl 

File Name  :  
com/bethecoder/tutorials/freemarker/common/Student.java 
   
package com.bethecoder.tutorials.freemarker.common;

public class Student {

  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public String toString() {
    return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/freemarker/tests/ObjectListTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.freemarker.tests;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bethecoder.tutorials.freemarker.common.Student;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ObjectListTest {

  /**
   @param args
   @throws IOException 
   @throws TemplateException 
   */
  public static void main(String[] argsthrows IOException, TemplateException  {

    //Get template from classpath
    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(ObjectListTest.class, "/");
    Template template = cfg.getTemplate("objlist.ftl");
    
    //Prepare data model
     Student std1 = new Student("Sriram"2"Chess");
     Student std2 = new Student("Sudhakar"29"Painting");
     Student std3 = new Student("Anu"28"Cooking");
     List<Student> students = Arrays.asList(std1, std2, std3);
          
    Map<String, Object> dataModel = new HashMap<String, Object>();
    dataModel.put("students", students);
    
    //Merge template and data
    OutputStreamWriter output = new OutputStreamWriter(System.out);
    template.process(dataModel, output);
  }
}
   

It gives the following output,
Name : Sriram
Age : 2
Hobby : Chess

Name : Sudhakar
Age : 29
Hobby : Painting

Name : Anu
Age : 28
Hobby : Cooking


                    Print

   



Books Recommendation

 
 
bl  br