Suppose you have a list of student names and now you need to output that list student names using Apache FreeMarker. So how do we do it? Let’s find out in this tutorial.
First, I will create a new Maven project as an example:
Apache FreeMarker dependency:
1 2 3 4 5 |
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.27-incubating</version> </dependency> |
The list.ftl file has no content and it will be used as an Apache FreeMarker template.
Application class has the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.huongdanjava.freemarker; import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class Application { public static void main(String[] args) { Configuration configuration = new Configuration(Configuration.VERSION_2_3_27); configuration.setClassForTemplateLoading(Application.class, "/"); try { Template template = configuration.getTemplate("list.ftl"); StringWriter writer = new StringWriter(); Map<String, Object> map = new HashMap<String, Object>(); map.put("names", Arrays.asList("Khanh", "Nguyen", "Tan")); template.process(map, writer); System.out.println(writer); } catch (Exception e) { e.printStackTrace(); } } } |
As you can see, in the main() method of the Application class, we have a created Configuration object with version 2.3.27 and a Template object using our template file.
Now, to be able to output the list of student names that I have passed into the code above, I will add the contents to the template file list.ftl as follows:
1 2 3 |
<#list names as name> ${name} </#list> |
In the code above, I used the <#list> tag of Apache FreeMarker to navigate through all the elements of the student names, assign the value of each element to the variable name, then output the value of this variable uses placeholder ${name}.
Result: