Detecting first and last item inside a Groovy each{} closure

本小妞迷上赌 提交于 2019-11-28 23:56:02

问题


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

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

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.

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


回答1:


You could use

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

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



回答2:


The answer provided by sbglasius may lead to incorrect result like when the list contains redundants elements so an element from inside the list may equals the last one.

I'm not sure if sbglasius could use is() instead of == but a correct answer could be :

myList.eachWithIndex{ elt, i ->
  if(i == 0) {
   // First element
  }

  if(i ==  myList.size()-1) {
   // Last element
  }
}



回答3:


if (it.after.value != null) { ...... }

Works for maps



来源:https://stackoverflow.com/questions/4012538/detecting-first-and-last-item-inside-a-groovy-each-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!