user2474969
user2474969

Reputation: 25

Loop using Jstl

I want to write a loop in JSTL code to print : Start 1 2 3 4 5 End Start 6 7 8 9 10 End... Start 96 97 98 99 100 End

I try to use this code :

<c:set var="start" value="Start"/>
<c:set var="end" value="End" />
<c:set var="count" value="0" />
<c:forEach items="${child.children}" var="c">

    <c:choose>
        <c:when test="${count == 0 }">
            ${start}<c:out value="${count}" /> <c:set
                    var="count" value="${count + 1}" />
            ${end}</c:when>
            <c:when test="${count % 5 == 0}">
                   ${start}<c:out value="${count}" />
                        <c:set var="count" value="${count + 1}" />
                   ${end}
                </c:when> <c:otherwise>
                    <c:out value="${count}" />
                    <c:set var="count" value="${count + 1}" />
                </c:otherwise>
        </c:when>
    </c:choose>
</c:forEach>

but it does not work !

Upvotes: 0

Views: 1752

Answers (1)

Marlon Bernardes
Marlon Bernardes

Reputation: 13843

The following code does what you want:

<c:forEach var="i" begin="1" end="100" step="1">
  <c:set var="end" value="${i} End"/>
  ${i == 1 ? 'Start' : ''}
  ${i % 5 == 0 ? end : i }
  ${i % 5 == 0 && i != 100 ? 'Start' : ''}
</c:forEach>

Output:

Start 1 2 3 4 5 End Start 6 7 8 9 10 End Start 11 12 13 14 15 End Start 16 17 18 19 20 End Start 21 22 23 24 25 End Start 26 27 28 29 30 End Start 31 32 33 34 35 End Start 36 37 38 39 40 End Start 41 42 43 44 45 End Start 46 47 48 49 50 End Start 51 52 53 54 55 End Start 56 57 58 59 60 End Start 61 62 63 64 65 End Start 66 67 68 69 70 End Start 71 72 73 74 75 End Start 76 77 78 79 80 End Start 81 82 83 84 85 End Start 86 87 88 89 90 End Start 91 92 93 94 95 End Start 96 97 98 99 100 End

Don't forget to import JSTL taglib:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Upvotes: 2

Related Questions