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

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() {
      th('class':'l name', 'name')
      th('class':'type', 'type')
  tbody() {
    // Add a row to the table for each item in myList
    myList.each {
      tr('class' : '????????') {
        td('class':'l name',
        td('class':'type', it.type)

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


You could use

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

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

Need Your Help

HTML Canvas Full Screen

javascript html5 canvas

I'm playing with the following application using the HTML Canvas:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.