我正在使用 Groovy 方便的 MarkupBuilder 从各种源数据构建 HTML 页面。
我努力做好的一件事是构建一个 HTML 表格并将不同的样式类应用到第一行和最后一行。这可能最好用一个例子来说明......
table() {
thead() {
tr(){
th('class':'l name', 'name')
th('class':'type', 'type')
th('description')
}
}
tbody() {
// Add a row to the table for each item in myList
myList.each {
tr('class' : '????????') {
td('class':'l name', it.name)
td('class':'type', it.type)
td(it.description)
}
}
}
}
在<tbody>
部分,我想设置 <tr>
的类元素根据当前项目是否在 myList
中而有所不同。是第一项或最后一项。
有没有一种很好的 Groovy 化方法来做到这一点,而无需借助于手动检查列表大小的项目索引,例如 eachWithIndex{}
?
最佳答案
你可以使用
if(it == myList.first()) {
// First element
}
if(it == myList.last()) {
// Last element
}
关于html - 检测 Groovy each{} 闭包中的第一个和最后一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4012538/