We can define multiple conditional checks using if-elseif-else directive.
Syntax
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
...
<#else>
...
</#if>
studentGrades.ftl
<#if marks < 35 > You are failed <#elseif marks < 50> You are passed and got third class <#elseif marks < 60> You are passed and got second class <#elseif marks < 70> You are passed and got first class <#else> You are passed and got distinction </#if>
Step 1: 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);
}
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 2: Define StudentGradePopulator.
package com.sample.app;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import com.sample.app.util.FreeMarkerUtil;
public class StudentGradePopulator {
public static void main(String args[]) throws Exception {
Map<String, Object> modelObject = new HashMap<String, Object>();
modelObject.put("marks", 30);
StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
System.out.println(stringWriter.toString().trim());
modelObject.put("marks", 50);
stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
System.out.println(stringWriter.toString().trim());
modelObject.put("marks", 70);
stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
System.out.println(stringWriter.toString().trim());
modelObject.put("marks", 80);
stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "studentGrades.ftl");
System.out.println(stringWriter.toString().trim());
}
}
Output
You are failed
You are passed and got second class
You are passed and got distinction
You are passed and got distinction
No comments:
Post a Comment