Wednesday, 24 June 2020

Free Marker: #include directive

‘include’ directive is used to insert the content of other file into the template.

 

Syntax

<#include path>
or
<#include path options>

copyright.ftl

---------------------------------------------------------------------------------
All these examples are owned by https://self-learning-java-tutorial.blogspot.com/
You can use these examples and share to others also

Author: Krishna
Date: ${today}
---------------------------------------------------------------------------------

includeDemo.ftl

<#include "/copyright.ftl">

Hello ${name}, Welcome to our Application.

Define ‘FreeMarkerUtil’ class that takes 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);
	}

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

}

IncludeDemoPopulator.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 IncludeDemoPopulator {
	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, "includeDemo.ftl");
		System.out.println(stringWriter.toString().trim());

	}
}

Output

---------------------------------------------------------------------------------
All these examples are owned by https://self-learning-java-tutorial.blogspot.com/
You can use these examples and share to others also

Author: Krishna
Date: Fri May 22 23:51:28 IST 2020
---------------------------------------------------------------------------------
Hello Krishna, Welcome to our Application.



Previous                                                    Next                                                    Home

No comments:

Post a Comment