Sunday 27 March 2016

Iteration of a Collection in Freemarker Template

In this blog , we will be demonstrating the iteration of Java Collection viz. Map , List etc with the different examples in the freemarker templates. As all the Java collection implements the Iterable interface, so iteration technique is same for different sort of collections.

    




1. Iteration of a Map in Freemarker Template (FTL)

Lets look how the Map iteration looks like in Java : 

Map<String,Object> personMap = new HashMap<String, Object>();
person.put("name","sachin");
person.put("age, 29);
person.put("occupation","blogger");
for (String key : person.keySet()) {
           System.out.println("key=" + key + ", value=" + person.get(key));
}

Similar Map if we need to iterate in freemarker template then it's as follow: 

<#if personMap?has_content>
<#list personMap?keys as key>
"keys= "${key}, "value=" ${personMap[key]}; 
</#list>
</#if>

Here ?keys is a built-in function in freemarker just like keySet() in Java to 
provide the list of all the keys.

Output :
---------------------------------------
key=name, value=sachin
key=age, value=29
key=occupation, value=blogger
---------------------------------------

2. Iteration of a List in Freemarker Template (FTL)

Lets look how the List iteration looks like in Java 

List<String> nameList = new ArrayList<>();
nameList.add("Amar");
nameList.add("Akbar");
nameList.add("Anthony");
for (String name : nameList) {
System.out.println("name=" + name);
}

Similar List if we need to iterate in freemarker template then it's as follow: 

<#if nameList?has_content>
<#list nameList as name>
"name= "${name}
</#list>
</#if>

Output:
-------------------
name=Amar
name=Akbar
name=Anthony
--------------------------

Here has_content is a built-in function in freemarker just to check the emptiness 
of the collection return true if non-empty else return false.


Enjoy the power of the freemarker template for various purpose like Email Templating , View part of the framework , Generating News Feed etc .

1 comment:

  1. Thanks but i have a question, what if the value of a key has another hashmap? then ${personMap[key]} throws an error for that particular key

    ReplyDelete