2

I have got a map where the key is a object but the value is a list object. I am using play framework 1.4.2 (using groovy template).

This is the map:

Map<Object, List<Object>> map = new HashMap<>();

How can iterating through the map values in a template?

2 Answers2

2

You can use entrySet() to iterate over the map just like you would do in java (see this SO answer), then create a variable in a groovy script to get the value and key :

#{list items:map.entrySet(), as:'set' }
  ∗{print the key}*
  ${set.key}
  *{iterate over value list }∗
  #{list items: set.value, as:'itemValue'}
    ${itemValue}
  #{/list}

#{/list}

For more information about groovy scripts in play see : Play documentation

g.annunziata
  • 3,118
  • 1
  • 24
  • 25
1

To walk through the map values you need to get values by calling Map#values() as follows:

#{list map.values()}
Value of your map is ${_}
#{/list}

To walk through values of your lists of values of your map, you need to use list tag twice as follows:

#{list map.values()}
  #{list _}
    Value of your list is ${_}
  #{/list}
  #{else}Your list is empty#{/else}
#{/list}

Other useful examples of using list tag you can find in a cheatsheet of play documentation, for example:

#{list items:0..10, as:'i'} 
  ${i} 
#{/list}

#{list items:'a'..'z', as:'l'}
  ${l} ${l_isLast ?'':'|' }
#{/list}

#{list users}
  ${_}
#{/list}

Loop constructs
#{list items:task, as:'task'}
  ${task}
#{/list}
#{else}No tasks on the list#{/else}
Tip: Else can be used along with list
Aleksei Sotnikov
  • 633
  • 4
  • 15