Freemarker iterating over hashmap keys

Viewed 122365

Freemarker has two collection datatypes, lists and hashmaps Is there a way to iterate over hashmap keys just as we do with lists?

So if I have a var with data lets say:

user : {
  name : "user"
  email : "looser@everything.com"
  homepage : "http://nosuchpage.org"
}

I would like to print all the user's properties with their value. This is invalid, but the goal is clear:

<#list user.props() as prop>
  ${prop} = ${user.get(prop)}
</#list>
7 Answers

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

So the most convenient way to iterate a map is:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...> wrappers.

Related