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!
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>
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] %>
...
<% } %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With