Wednesday, 24 June 2020

FreeMarker: ?int built-in: Get division result as integer

?int built-in is used to get the integer part of the result of a division.

 

Find the below working application.

 

Step 1: Create intBuiltin.ftl file under src/main/resources/templates folder.

 

intBuiltin.ftl

<#assign x = 21>

x/2 -> ${(x/2)?int}

1.1 -> ${1.1?int}
1.99 -> ${1.99?int}
-1.1 -> ${-1.1?int}
-1.99 -> ${-1.99?int}

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 IntBuiltInPopulator.

 

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

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

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

	}
}

Output

x/2 -> 10

 

1.1 -> 1

1.99 -> 1

-1.1 -> -1

-1.99 -> -1




Previous                                                    Next                                                    Home

No comments:

Post a Comment