tom*_*nor 28 html groovy closures markupbuilder
我正在使用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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在本<tbody>节中,我想<tr>根据当前项目myList是第一项还是最后一项来将元素的类设置为不同的类.
是否有一个很好的Groovy-ified方法来做到这一点,而不是使用手动来检查项目索引与列表大小使用类似的东西eachWithIndex{}?
sbg*_*ius 49
你可以用
if(it == myList.first()) {
// First element
}
if(it == myList.last()) {
// Last element
}
Run Code Online (Sandbox Code Playgroud)
小智 14
sbglasius提供的答案可能会导致错误的结果,例如当列表包含冗余元素时,列表中的元素可能等于最后一个元素.
我不确定sbglasius是否可以使用is()而不是==正确的答案可能是:
myList.eachWithIndex{ elt, i ->
if(i == 0) {
// First element
}
if(i == myList.size()-1) {
// Last element
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13815 次 |
| 最近记录: |