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

荒凉一梦 提交于 2019-12-23 18:46:39

问题


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.


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/1636174/grails-testing-for-the-first-element-in-a-set-using-gsp-each

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!