Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Map using playframework template system (groovy)

I've been using the--quite excellent--playframework and have had trouble finding documentation/examples on how to access a Map data structure from a view, using play's template engine.

To be even more specific, I wish to access the Map as I iterate over a List of objects, e.g.,

#{list items:itemList, as:'item'}
 // access the map value using the ${item?.id} as the key
#{/list}

Thank's for looking.

like image 903
meta.matt Avatar asked Jul 19 '11 15:07

meta.matt


2 Answers

This is a generic solution to iterate on Map in using Play! Framework:

in the controller :

render(map);

in the template:

#{list items:map.keySet(), as:'key'}
   ${map.get(key)}
#{/list}

The fact that you want to rely on a side List to iterate on your Map suggest me that you are searching a predictible way for your iteration process.

In that case, just remember that iteration will be unpredictable if you don't use an ordered/sorted Map implementation.

  • HashMap gives you an unsorted, unordered Map
  • LinkedHashMap maintains insertion order
  • TreeMap is the only JDK implementation of a sorted Map. By default it allows you to iterate following the natural order of the elements. You can also specify a custom sort order and implements the Comparable interface. This will lead you to override the compareTo() method.
like image 90
oxymesis Avatar answered Nov 16 '22 13:11

oxymesis


Assuming you do in the Controller:

render(map, itemList); //map is a Map

This should work:

#{list items:itemList, as:'item'}
 // access the map value using the ${item?.id} as the key
 ${map.get(item.?id)}
#{/list}
like image 26
Pere Villega Avatar answered Nov 16 '22 13:11

Pere Villega