JSTL: iterate list but treat first element differently

D.C. picture D.C. · Jan 7, 2010 · Viewed 38.6k times · Source

I'm trying to process a list using jstl. I want to treat the first element of the list differently than the rest. Namely, I want only the first element to have display set to block, the rest should be hidden.

What I have seems bloated, and does not work.

Thanks for any help.

<c:forEach items="${learningEntry.samples}" var="sample">
    <!-- only the first element in the set is visible: -->
    <c:if test="${learningEntry.samples[0] == sample}">
        <table class="sampleEntry">
    </c:if>
    <c:if test="${learningEntry.samples[0] != sample}">
        <table class="sampleEntry" style="display:hidden">
    </c:if>

Answer

axtavt picture axtavt · Jan 7, 2010

It can be done even shorter, without <c:if>:

<c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
    <table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}> 
</c:forEach>