Using [], we can specify list elements directly in the template.
listLiteral.ftl
<#list ["2", "3", "foo", 1.234] as x>
Value of element is : ${x}
</#list>
Define ‘FreeMarkerUtil’ class that takes 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 ‘ListLiteralPoplator.java’.
ListLiteralPoplator.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 ListLiteralPoplator {
public static void main(String args[]) throws Exception {
Map<String, Object> modelObject = new HashMap<String, Object>();
StringWriter stringWriter = FreeMarkerUtil.mergeModelAndTemplate(modelObject, "listLiteral.ftl");
System.out.println(stringWriter.toString().trim());
}
}
Run the application, you will see below messages in the console.
Value of element is : 2 Value of element is : 3 Value of element is : foo Value of element is : 1.234
As you see above example, list is heterogeneous in Freemarker and it can handle different types of values.
No comments:
Post a Comment