Saturday 4 July 2020

FreeMarker: Access a character in string using index notation

You can access the individual character of a string using index notation.

 

Example

<#assign data="Hello World" >

 

data[0] return the character at index 0 which is ‘H’.

data[1] return the character at index 1 which is ‘e’.

 

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

 

stringIndexNotation.ftl
<#assign data="Hello World" >

Value at 0th index ${data[0]}
Value at 1st index ${data[1]}
Value at 2nd index ${data[2]}
Value at 3rd index ${data[3]}
Value at 4th index ${data[4]}

Step 2: Define ‘FreeMarkerUtil’ class that takes a model object 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 StringIndexNotationPopulator.

 

StringIndexNotationPopulator.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 StringIndexNotationPopulator {
	public static void main(String args[]) throws Exception {

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

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

	}
}

Output

Value at 0th index H
Value at 1st index e
Value at 2nd index l
Value at 3rd index l
Value at 4th index o

Previous                                                    Next                                                    Home

No comments:

Post a Comment