在Groovy each {}闭包中检测第一个和最后一个项目 [英] Detecting first and last item inside a Groovy each{} closure

查看:367
本文介绍了在Groovy each {}闭包中检测第一个和最后一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Groovy的便捷MarkupBuilder从各种源数据构建HTML页面.

I am using Groovy's handy MarkupBuilder to build an HTML page from various source data.

我努力做到的一件事是建立一个HTML表并将不同的样式类应用于第一行和最后一行.最好用一个例子来说明这一点...

One thing I am struggling to do nicely is build an HTML table and apply different style classes to the first and last rows. This is probably best illustrated with an example...

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中的当前项目是第一项还是最后一项.

In the <tbody> section, I would like to set the class of the <tr> element to be something different depending whether the current item in myList is the first or the last item.

是否有一种很好的Groovy方式来做到这一点,而无需借助诸如eachWithIndex{}之类的手册来根据列表大小检查项目索引?

Is there a nice Groovy-ified way to do this without resorting to something manual to check item indexes against the list size using something like eachWithIndex{}?

推荐答案

您可以使用

if(it == myList.first()) {
   // First element
}

if(it == myList.last()) {
   // Last element
}

这篇关于在Groovy each {}闭包中检测第一个和最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆