Groovy / Grails - you need to get the list index value

I need to get the index position of each value in the list that I have. I do this so that I can display the gsp table with alternating row background colors. For instance:

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

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

+5
source share
2 answers

According to the documentation , g: every tag in the gsp view allows a "status" variable where grails stores 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>
+9
source

You can use any cycles g:each, eachWithIndexor for.

. css:

tr:nth-child(odd)  { background: #f7f7f7; }
tr:nth-child(even) { background: #ffffff; }

, :

<g:each status="i" in="${items}" var="item">
    ...
</g:each>

<% items.eachWithIndex { item, i -> %>
    ...
<% } %>

<% for (int i = 0; i < items.size(); i++) { %>
   <% def item = items[i] %>
   ...
<% } %>
+2

All Articles