开发者

Alternating row color in JSTL with nested loop

I would like to alternate row color for each row, I know how to alternate row color using varStatus in a forEach loop. However now, I've a nested l开发者_如何学运维oop.

<c:forEach var="aPermission" items="${Permissions}" varStatus="loop1">
    <c:forEach var="anIpRange" items="${aPermission.ipRanges}" varStatus="loop2">
    <tr class="${loop2.index % 2 == 0 ? 'row0' : 'row1'}"> [...]
    </c:forEach>
</c:forEach>

The code above is using only 'loop2' varStatus, and is only an approximation. How to solve the problem? I've to introduce my count variable or there are better ways?


Simply use a dedicated counter:

<c:set var="counter" value="${0}"/>
<c:forEach var="aPermission" items="${Permissions}" varStatus="loop1">
    <c:forEach var="anIpRange" items="${aPermission.ipRanges}" varStatus="loop2">
        <tr class="${counter % 2 == 0 ? 'row0' : 'row1'}"> [...] </tr>
        <c:set var="counter" value="${counter + 1}"/>
    </c:forEach>
</c:forEach>


  • store a sum of all iterated items (using <c:set>). You can do this in the outer loop by calculating currentSum = currentSum + fn:length(aPermission.ipRanges). Do this after the inner loop
  • use currentSum + loop2.index to check the color for each row.


There is an 1-line way.

UPD. I have been mistaken first time. there is the right solution without redundant variables.

<tr class="${(loop2.index*fn:length(aPermission.ipRanges) + loop1.index) % 2 == 0 ? 'row0' : 'row1'}">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜