![](/img/trans.png)
[英]How to use the index variable of a JSTL forEach loop to access a map entry?
[英]How to increment a loop variable with JSTL?
我想用jstl做这样的事情:
int i=0;
int j=0;
<c:forEach items="${commentNames}" var="comment">
<c:forEach items="${rates}" var="rate">
<c:if test="${i==j}">
int i++
</c:if>
</c:forEach>
int j++;
</c:forEach>
这是否可以与jstl一起使用?当我尝试这个时它会让我发现错误,我想知道是否有正确的方式来编写它
不是直接的,但你可以使用varStatus
把实例LoopTagStatus
在范围<c:forEach>
它提供了几个getter来解决循环索引以及它是循环的第一次还是最后一次迭代。
我只是不确定你的<c:if>
有意义,但我认为你实际上有两个相同大小的列表,其中包含评论名称和评论率,你需要只显示与评论相同的索引率。
<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">
${comment}
<c:forEach items="${rates}" var="rate" varStatus="rateLoop">
<c:if test="${commentLoop.index == rateLoop.index}">
${rate}
</c:if>
</c:forEach>
</c:forEach>
然而这很笨拙。 您可以直接通过索引更好地获得费率。
<c:forEach items="${commentNames}" var="comment" varStatus="commentLoop">
${comment}
${rates[commentLoop.index]}
</c:forEach>
更好的是创建一个具有name
和rate
属性的Comment
对象。
public class Comment {
private String name;
private Integer rate;
// Add/autogenerate getters/setters.
}
这样你就可以按如下方式使用它:
<c:forEach items="${comments}" var="comment">
${comment.name}
${comment.rate}
</c:forEach>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.