Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freemarker iterating over hashmap keys

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 : "[email protected]"   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> 
like image 235
tzador Avatar asked Sep 30 '09 12:09

tzador


People also ask

How do you create a list on Freemarker?

FreeMarker doesn't support modifying collections. But if you really want to do this in FreeMarker (as opposed to in Java), you can use sequence concatenation: <#assign myList = myList + [newItem]> . Here you create a new sequence that wraps the two other sequences.


1 Answers

Edit: Don't use this solution with FreeMarker 2.3.25 and up, especially not .get(prop). See other answers.

You use the built-in keys function, e.g. this should work:

<#list user?keys as prop>     ${prop} = ${user.get(prop)} </#list>   
like image 70
skaffman Avatar answered Sep 30 '22 23:09

skaffman