mwcz
mwcz

Reputation: 9311

Is it possible to reassign a loop index in a JSTL forEach loop?

Is it possible to reassign a loop index mid-loop, in order to skip iterations?

Toy example, to print a list of numbers 1,2,3,4,5,8,9,10:

<ul>
<c:forEach var="counter" begin="${1}" end="${10}">
    <li>${counter}</li>
    <c:if test="${counter eq 5}">
        <c:set var="counter" value="${counter+2}" /> <!-- skip two iterations -->
    </c:if>
</c:forEach>
</ul>

This example doesn't work. Is there a way to make it work?

I'm not suggesting this is a good idea, I only want to know if it's possible.

Upvotes: 1

Views: 815

Answers (1)

BalusC
BalusC

Reputation: 1108972

No.

Depending on the concrete functional requirement, you need to solve it differently. For example, just only print the iterated item when the condition really matches.

<c:forEach var="counter" begin="${1}" end="${10}">
    <c:if test="${counter lt 6 or counter gt 7}">
        <li>${counter}</li>
    </c:if>
</c:forEach>

Upvotes: 2

Related Questions