Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 253
grantmcconnaughey Avatar asked Feb 07 '13 19:02

grantmcconnaughey


2 Answers

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>
like image 181
Miguel Prz Avatar answered Oct 24 '22 20:10

Miguel Prz


Any of g:each, eachWithIndex, or for loops can be used.

But, for this specific case, the index value is not needed. Using css pseudo-classes is recommended:

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

If you still need to get the index, options are:

<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] %>
   ...
<% } %>
like image 34
musa Avatar answered Oct 24 '22 20:10

musa