Search code examples
listgrailsgroovyindexing

Groovy/Grails - Need to retrieve List index value


I need to retrieve the index position of each value in a list I have. I'm doing this so that I can display a gsp table with alternating row background colors. For example:

(list.indexVal % 2) == 1 ? 'odd' : 'even'

How can I get the index position number of each item in a Groovy list? Thanks!


Solution

  • According the documentation, the g:each tag in the gsp view allows the "status" variable where grails store the iteration index in. Example:

    <tbody>
      <g:each status="i" in="${itemList}" var="item">
        <!-- Alternate CSS classes for the rows. -->
        <tr class="${ (i % 2) == 0 ? 'a' : 'b'}">
          <td>${item.id?.encodeAsHTML()}</td>
          <td>${item.parentId?.encodeAsHTML()}</td>
          <td>${item.type?.encodeAsHTML()}</td>
          <td>${item.status?.encodeAsHTML()}</td>
        </tr>
      </g:each>
    </tbody>