Interpolations are used to insert the value of an expression converted to text.
Syntax
${expression}
Interpolation can be used in two places.
a. Inside the text: Hello ${name}!
b. Inside String literal: <#include "/header/${org}.txt">
The result of interpolated string must be one of these values.
a. String
b. Number
c. Date-time value
If you want to use other values like Boolean in interpolation, you should convert them explicitly.
Example
${b?string("yes", "no")}
Above statement evaluate to "yes" if the variable ‘b’ is true, else "no".
Find the below working application.
Step 1: Create ‘interpolations.ftl’ file under src/main/resources/templates folder.
interpolations.ftl
<#assign a = 10, b = true, c = false, d = 123.45>
a : ${a}
b : ${b?string("yes", "no")}
c : ${c?string("yes", "no")}
d : ${d}
"a : ${a}"
"b : ${b?string("yes", "no")}"
"c : ${c?string("yes", "no")}"
"d : ${d}"
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 InterpolationPopulator.
InterpolationPopulator.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 InterpolationPopulator {
public static void main(String args[]) throws Exception {
Map<String, Object> modelObject = new HashMap<String, Object>();
StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "interpolations.ftl");
System.out.println(stringWriter.toString().trim());
}
}
Output
a : 10 b : yes c : no d : 123.45 "a : 10" "b : yes" "c : no" "d : 123.45"
No comments:
Post a Comment