Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL: iterate list but treat first element differently

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>
like image 623
D.C. Avatar asked Jan 07 '10 02:01

D.C.


2 Answers

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> 
like image 177
axtavt Avatar answered Nov 09 '22 14:11

axtavt


Yes, declare varStatus="stat" in the foreach element, so you can ask it if it's the first or the last. Its a variable of type LoopTagStatus.

This is the doc for LoopTagStatus: http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html It has more interesting properties...

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

Edited: copied from axtavt

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> 
like image 27
helios Avatar answered Nov 09 '22 15:11

helios