FreeMarker Iterate List

FreeMarker Iterate List

In previous tutorial you saw how to set up project and use FreeMarker template, print Hello World. Here you will see how to iterate list object in FreeMarker template. If you want to set up project please copy it from previous tutorial.

Important: You will have to include freemarker.x.x.x.jar in your classpath to use FreeMarker template

  • FreeMarker template with list data iteration example FreeMarkerHelloWorld.ftl:
FreeMarker Template Iterate List: ${name}

<#list personDetails as person>
${person}
</#list>
  • FreeMarkerGenrateDataFromObject.java:
package com.javahonk;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

public class FreeMarkerGenrateDataFromObject {
	
	private static Configuration cfg = null;
	
	static{		
		// Freemarker below configuration object deprecated
		//Configuration cfg = new Configuration();
		//Please use this. To make it backward compatible. Please visit here for more info: 
		//http://freemarker.org/docs/api/freemarker/template/Configuration.html
		cfg = new Configuration(new Version("2.3.0"));
	}
	
	public static void main(String[] args) {

		try {
			// Load template
			Template template = cfg.getTemplate("resources/FreeMarkerHelloWorld.ftl");

			// Create data for template
			Map<String, Object> templateData = new HashMap<String, Object>();
			templateData.put("name", "Java Honk");
			
			List<String> personDetails = new ArrayList<String>();
			personDetails.add("First Name: Java");
			personDetails.add("Last Name: Honk");
			personDetails.add("Location: NY");			

			templateData.put("personDetails", personDetails);

			// Write output on console example 1
			StringWriter out = new StringWriter();
			template.process(templateData, out);
			System.out.println( out.getBuffer().toString() );
			out.flush();
			
			// Write output on console example 2
			/*Writer out = new OutputStreamWriter(System.out);
			template.process(templateData, out);
			out.flush();*/

			// Write data to the file
			Writer file = new FileWriter(new File("C:\\JavaHonk\\WriteListDataToFile.txt"));
			template.process(templateData, file);
			file.flush();
			file.close();

		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
  • Output:

FreeMarker Iterate List

Leave a Reply

Your email address will not be published. Required fields are marked *