Sunday 21 June 2020

FreeMarker: list or sequence slicing

Slicing is used to get the sub sequence.

 

For example, for the sequence ["A", "B", "C", "D", "E", "F"].

seq[1..*3] = AB

seq[1..<3] = AB

seq[1..*2] = BC

seq[1..] = BCDEF

 

Range Expression

Description

Example

start..end

Range from star number to end (inclusive)

seq[1..*3] = AB

 

start..<end or start..!end:

Range from start number to end (exclusive)

seq[1..<3] = AB

 

start..*length

Range from start to length number of items.

seq[1..*2] = BC

 

start..

Unbounded range.

seq[1..] = BCDEF

 

Find the below working application.

 

Step 1: Define listSlicing.ftl file under src/main/resources/templates folder.

 

listSlicing.ftl
<#assign seq = ["A", "B", "C", "D", "E", "F"]>

seq : <#list seq as item>${item}</#list>

- seq[1..*3] : <#list seq[0..*2] as i>${i}</#list>
- seq[1..<3] : <#list seq[0..*2] as i>${i}</#list>
- seq[1..*2] : <#list seq[1..*2] as i>${i}</#list>
- seq[1..] : <#list seq[1..] as i>${i}</#list>

Step 2: 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);
		FREE_MARKER_CONFIGURATION.setFallbackOnNullLoopVariable(false);
	}

	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 3: Define ListSlicingPopulator.

 

ListSlicingPopulator.java
package com.sample.app;

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

import com.sample.app.util.FreeMarkerUtil;

public class ListSlicingPopulator {
	public static void main(String args[]) throws Exception {

		Map<String, Object> modelObject = new HashMap<String, Object>();

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

	}
}

Output

seq : ABCDEF

 

- seq[1..*3] : AB

- seq[1..<3] : AB

- seq[1..*2] : BC

- seq[1..] : BCDEF





Previous                                                    Next                                                    Home

No comments:

Post a Comment