Sunday 21 June 2020

FreeMarker: #sep directive

#sep directive is used to print something between the items of a sequence (not before the first item or after the last item).

 

For example,

 

countryNames.ftl

<#list countryNames as countryName>${countryName}<#sep>, </#list>

Above snippet print country names like below.

India, Nepal, Sri Lanka, Germany

 

Step 1: Define ‘FreeMarkerUtil’ class that take model class and template file as input and merge them.

 

FreeMarkerUtil.java

package com.sample.app.util;

import java.io.StringWriter;
import java.util.Locale;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerUtil {

	private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);

	static {
		FREE_MARKER_CONFIGURATION.setClassForTemplateLoading(FreeMarkerUtil.class, "/templates/");
		FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
		FREE_MARKER_CONFIGURATION.setLocale(Locale.US);
		FREE_MARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public static StringWriter mergeModelAndTemplate(Object modelObject, String ftlFile) throws Exception {
		StringWriter stringWriter = new StringWriter();

		Template template = FREE_MARKER_CONFIGURATION.getTemplate(ftlFile);

		template.process(modelObject, stringWriter);

		return stringWriter;
	}

}

Step 2: Define CountryNamesPopulator.

 

CountryNamesPopulator.java

package com.sample.app;

import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sample.app.util.FreeMarkerUtil;

public class CountryNamesPopulator {
	public static void main(String args[]) throws Exception {
		List<String> countryNamesList = Arrays.asList("India", "Nepal", "Sri Lanka", "Germany");

		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("countryNames", countryNamesList);

		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "countryNames.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

India, Nepal, Sri Lanka, Germany





Previous                                                    Next                                                    Home

No comments:

Post a Comment