Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - Testing for the first element in a set using gsp each

Tags:

grails

gsp

Does anyone know how to test for the first member and last member in a gsp loop?

Here's my jsp code:

<c:forEach items='${aSet}' var='elem' varStatus="loop">
   <c:if test='${loop.first}'>
      <p>Display something</p>
   </c:if>
</c:forEach>

I know you can test for status in a g:each statement but that's just an integer. Is there anything to access the first and last element? If not, is there another way to do what I'm doing?

Any help appreciated.

like image 759
Matt Avatar asked Nov 24 '25 09:11

Matt


2 Answers

I'm not sure what the problem with <g:each status> is. Yes, it's "just" an integer, but isn't that exactly what you want?

<g:each in="${aSet}" var="elem" status="i">
    <g:if test="${i == 0}">
        <p>Display something for first element</p>
    </g:if>
    <p>Stuff that is always displayed</p>
    <g:if test="${i == aSet.size() - 1}">
        <p>Display something for last element</p>
    </g:if>
</g:each>
like image 92
Daniel Rinser Avatar answered Nov 28 '25 00:11

Daniel Rinser


This question is a bit old, but another way to perform this check is to use Groovy List's first() method. You can also do the same thing for the last element using Groovy List's last() method.

list.first()

<g:forEach items='${aSet}' var='elem' varStatus="loop">
   <g:if test='${elem == aSet.first()}'>
      <p>Display something for first element</p>
   </g:if>
</g:forEach>

list.last()

<g:forEach items='${aSet}' var='elem' varStatus="loop">
   <g:if test='${elem == aSet.last()}'>
      <p>Display something for last element</p>
   </g:if>
</g:forEach>
like image 40
dspies Avatar answered Nov 28 '25 01:11

dspies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!