Working with List/Array and HashMap in FreeMarker

Its a normal thing that we get confused between looping when we are using list, hashmap or array in freemarker .As the syntax differ for each things in freemarker. It also happens that when we want to generate JSON from java collection, we need to append comma on each iteration except the last one.Identifying an last iteration is also an issue when we use freemarker. Its not much difficult, its just we are not concentrating on syntax.

So lets look on the syntax of each one.

Iterating Array or Sequence(generally its any type of List) in freemarker
    <#list ArrayOrListOfusers as user> <li>${user} </#list>

Iterating Hashmap in freemarker

When we are dealing with hashmap type of object, There are 2 values getting stored in side an item of hashmap.There are some technical scenarios in which we need only list values , We need only key of hashmap etc...
  • list HashMap?keys as key ==> In this loop, variable key will represent the keys in haspmap
  • list HashMap?values as val==> In this loop, variable val will represent the Values in haspmap
  • list HashMap as key,val==> In this loop, variable key represents the value of key in hash map and val will represent the Value of values in haspmap
      <#list HashMap as keyItem,valItem> <li>${key}=${val} </#list>
    There are many cases where we need to append comma after each iteration and on the last iteration we need to ignore it.This is kind of bit tricky in freemarker if we create one local variable as counter and manage it for last iteration.Luckily we have flag available in freemarker for checking the last iteration.So let's take look on that.
  • item_index (deprecated by item?index): Index of current item in the loop.
  • item_has_next (deprecated by item?has_next): Boolean value that tells if the current item is the last in the sequence or not.

  • Share this:



    Post a Comment