2010-01-07 2 views
20

Ich versuche, eine Liste mit jstl zu verarbeiten. Ich möchte das erste Element der Liste anders behandeln als den Rest. Ich möchte nämlich nur das erste Element anzeigen lassen, das blockiert werden soll, der Rest sollte ausgeblendet werden.JSTL: Liste iterieren aber erstes Element anders behandeln

Was ich habe scheint aufgebläht, und funktioniert nicht.

Danke für jede Hilfe.

<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> 

Antwort

44

Es c ein getan werden noch kürzer, ohne <c:if>:

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

Basierend auf Anwendungsfall Sie auch, wenn Anweisung innerhalb der foreach-Schleife verwenden können '' – davidcondrey

5

Ja, varStatus = "stat" in der foreach-Element deklarieren, können Sie es so fragen, ob es das erste oder das letzte ist. Es ist eine Variable vom Typ LoopTagStatus.

Dies ist die doc für LoopTagStatus: http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html Es hat mehr interessante Eigenschaften ...

<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> 

Editiert: kopiert von axtavt

Es noch kürzer gemacht werden kann, ohne <c:if>:

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