Wednesday 24 June 2020

FreeMarker: Built-ins

Built-ins are just like methods in java. Freemarker provide lot of built-ins you can use while constructing the template files.

https://freemarker.apache.org/docs/ref_builtins.html

 

How to access built-ins?

Using ?, we can access built-ins.

 

For example, userName?upper_case will give the uppercase version of the user name.

 

builtIns.ftl

Hello ${name?upper_case}, your name has ${name?length} characters.

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;
	}

}

Define BuiltInPopulator.

 

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

		Map<String, Object> modelObject = new HashMap<String, Object>();
		modelObject.put("name", "Krishna");
		
		StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "builtIns.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

Hello KRISHNA, your name has 7 characters.

 

You can see list of all Built-ins from the below link.

https://freemarker.apache.org/docs/ref_builtins.html

 



Previous                                                    Next                                                    Home

No comments:

Post a Comment