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

10
我一直在使用非常优秀的Play框架,但在如何使用Play模板引擎从视图中访问Map数据结构方面,我遇到了一些困难,而且很难找到相关文档/示例。
更具体地说,我希望在迭代对象列表时访问Map。例如:
#{list items:itemList, as:'item'}
 // access the map value using the ${item?.id} as the key
#{/list}
感谢查看。
4个回答

21

这是一个通用解决方案,用于在Play!框架中迭代Map

在控制器中:

render(map);

在模板中:

#{list items:map.keySet(), as:'key'}
   ${map.get(key)}
#{/list}
你希望依靠一个List来迭代你的Map,这表明你正在寻找迭代过程的可预测方法。在这种情况下,请记住,如果您不使用有序/排序的Map实现,则迭代将是不可预测的。
  • HashMap为您提供了一个无序的未排序的Map
  • LinkedHashMap维护插入顺序
  • TreeMap是唯一的JDK实现了一个有序的Map。默认情况下,它允许您按照元素的自然顺序进行迭代。您还可以指定自定义排序顺序并实现Comparable接口。这将导致您重写compareTo()方法。

5
假设您在控制器中进行操作:
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}

0

我对Play框架一无所知,但这在GSP中可以工作

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

0

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

*{ 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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接