如何使用playframework模板系统(groovy)访问地图

如何使用playframework模板系统(groovy)访问地图,groovy,playframework,Groovy,Playframework,我一直在使用非常优秀的playframework,在使用play的模板引擎从视图访问地图数据结构的文档/示例中遇到了困难 更具体地说,我希望在遍历对象列表时访问地图,例如 #{list items:itemList, as:'item'} // access the map value using the ${item?.id} as the key #{/list} 感谢您的关注。假设您在控制器中进行了以下操作: render(map, itemList); //map is a Map

我一直在使用非常优秀的playframework,在使用play的模板引擎从视图访问地图数据结构的文档/示例中遇到了困难

更具体地说,我希望在遍历对象列表时访问地图,例如

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

感谢您的关注。

假设您在控制器中进行了以下操作:

render(map, itemList); //map is a Map
这个应该可以工作:

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

我对play框架一无所知,但这在GSP中是可行的

#{list items:itemList, as:'item'}
 ${map[item?.id]}
#{/list}

我在地图上做类似的事情:

*{ Map<User, Integer> shareHolders = ... }*
#{list shareHolders.sort{it.value}.collect {k,v -> k}.reverse(), as:'holder'}
    <tr>
        <td>${holder.name}</td>
        <td>${shareHolders[holder]}</td>
    </tr>
#{/list}
*{Map股东=…}*
#{列出股东。排序{it.value}。收集{k,v->k}.reverse(),作为:'holder'}
${holder.name}
${股东[持有人]}
#{/list}
这是一个使用Play在地图上迭代的通用解决方案!框架:

在控制器中:

render(map);
在模板中:

#{list items:map.keySet(), as:'key'}
   ${map.get(key)}
#{/list}
您希望依靠一个侧列表在地图上迭代的事实表明,您正在为迭代过程寻找一种可预测的方法。 在这种情况下,只要记住,如果不使用有序/排序映射实现,迭代将是不可预测的。

  • HashMap提供了一个未排序、无序的映射
  • LinkedHashMap维护插入顺序
  • TreeMap是唯一一个排序映射的JDK实现。默认情况下,它允许您按照元素的自然顺序进行迭代。还可以指定自定义排序顺序并实现该接口。这将导致您重写compareTo()方法。