2010-01-07 39 views
20

我正在嘗試使用jstl處理列表。我想把列表中的第一個元素與其他元素區別開來。也就是說,我只想要第一個元素將顯示設置爲阻止,其他應該隱藏。JSTL:迭代列表,但不同地對待第一個元素

我現在看起來臃腫,並且不起作用。

感謝您的任何幫助。

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

回答

44

它命名爲c一個做甚至更短,無<c:if>

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

根據使用情況,你也可以使用一個語句的時候foreach循環裏面'' – davidcondrey 2015-02-04 18:53:25

5

是,宣佈在foreach元素varStatus =「統計」,所以你可以要求它,如果它是第一個還是最後一個。它是一個LoopTagStatus類型的變量。

這是LoopTagStatus商務部: http://java.sun.com/products/jsp/jstl/1.1/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html 它有更多有趣的屬性...

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

編輯:從axtavt複製

這是可以做到更短,無<c:if>

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