html - 检测 Groovy each{} 闭包中的第一个和最后一个项目

标签 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)
      }
    }
  }   
}

<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/

相关文章:

groovy - 使用 Groovy 将当前时间增加 1 小时

closures - 关闭需要唯一的访问权限

html - 使用 calc(100% - x) 会破坏 flex 布局

html - <ul> <li> 水平滚动

php - 如何在 Windows 中运行 "brew"命令?

循环内的 JavaScript 闭包 – 简单的实际示例

r - 环境、(en)closures 和框架是如何相关的?

html - 粘性菜单中的宽度调整不正确(响应式)

java - 如何在不使用 `dependsOn` 的情况下附加 Gradle 任务?

java - JasperReports 不适用于 Grails 2.4 : Could not initialize class net. sf.jasperreports.engine.xml.JRXmlDigesterFactory