[英]JSTL: iterate list but treat first element differently
I'm trying to process a list using jstl. 我正在尝试使用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>
It can be done even shorter, without <c:if>
: 它可以做得更短,没有<c:if>
:
<c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
<table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}>
</c:forEach>
Yes, declare varStatus="stat" in the foreach element, so you can ask it if it's the first or the last. 是的,在foreach元素中声明varStatus =“stat”,因此您可以询问它是第一个还是最后一个。 Its a variable of type LoopTagStatus. 它是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... 这是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>
Edited: copied from axtavt 编辑:从axtavt复制
It can be done even shorter, without <c:if>
: 它可以做得更短,没有<c:if>
:
<c:forEach items="${learningEntry.samples}" var="sample" varStatus = "status">
<table class="sampleEntry" ${status.first ? '' : 'style = "display:none"'}>
</c:forEach>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.