Iterate over map and get the next sequence value in Freemarker

Viewed 57

Freemarker has tmap collection data type, Is there a way to iterate over hashmap keys just as we do with lists and get sequence and next sequence value

My Data

user : {
  "fname" : "test1",
  "mname" : "test2",
  "lname" : "test3",
  "age" : "test4",
  "city" : "test5",
  "state" : "test6"
}

<table>
<tr>
<#list user.props() as key>
      <td>${key} : ${user.get(prop)}</td>
    </#list>
</tr>
</table>

Expected output like 2 key value pair in same row

fname : test1, mname : test2,
lname : test3, age : test4,
city : test5,  state : test6
1 Answers

Here are some examples about how to deal with hashes in freemarker. Keep in mind that:

  • there is no line feed on the examples, it would be nice to add some
    in case you're going to test them on your enviroment.
  • If your freemarker version is lower than 2.3.25 you have to comment/erase the incompatible examples: <#list ... as ..., ... >

Code example:

<#-- Creating a map -->
<#assign myMap = {
    "firstKey" : "firstValue",
    "second key" : 2,
    "3rdKey" : "third value" 
} />

<#-- getting a specific value -->
First value is: ${myMap.firstKey}
<#-- the above wouldn't work with the second key, since it has a space in its name -->
<#-- ${myMap.second key} does not work -->
<#-- getting a specific value (better option) -->
Second value is: ${myMap["second key"]}

<#-- checking your freemarker version -->
My freemarker version is ${.version}

<#-- iterating before version 2.3.25 -->
<#list myMap?keys as currentKey >
    Key: ${currentKey} - Value: ${myMap[currentKey]}
</#list>

<#-- iterating since version 2.3.25-->
<#list myMap as currentKey, currentValue >
    Key: ${currentKey} - Value: ${currentValue}
</#list>

<#-- going crazy with nested hashes (be carefull this can consume a lot of memory if abused) -->
<#assign myNestedMap = {
    "lowerCase" : {
        "1" : "a",
        "2" : "b"
    },
    "upperCase" : {
        "1" : "A",
        "2" : "B"
    } 
} />

${myNestedMap["lowerCase"]["2"]}
${myNestedMap["upperCase"]["1"]}

<#list myNestedMap as level_1_Key, level_1_Value >
    Map from ${level_1_Key}:
    <#list level_1_Value as level_2_Key, level_2_Value >
        Key: ${level_2_Key} - Value: ${level_2_Value}
    </#list>
</#list>

Here are 2 links from the official documentation that may help for further research:

Built-in's for hash

#list directive

Related