Search code examples
jspjstl

Contenante string which contains value of variable and strings in c:forEach loop in JSP


I want to achieve this:

  ['string1', -33.890542, 151.274856],
  ['string 2', -33.923036, 151.259052],
  ['string 3', -34.028249, 151.157507],
  ['string 4', -33.80010128657071, 151.28747820854187],
  ['string 5', -33.950198, 151.259302]

To achieve above output I have below code

<c:forEach items="${coordListEvent}" var="cor" varStatus="stat">
     <c:set var="chaine" value="     ['',${chaine}${cor.longitude},${cor.latitude}]," />
      </c:forEach>

but, I getting result

['',['',['',['',['',['',['',['',['',['',10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8162982],10.1803501,36.8

How can I modify my code to get expected output?


Solution

  • Use the <c:choose> JSTL tag to branch into an if-else construct based on the loop counter.

    <c:forEach items="${coordListEvent}" var="cor" varStatus="stat">
        <c:choose>
            <!-- IF -->
            <c:when test="${stat.count == 1}">
                <c:set var="chaine" value="[${cor.longitude},${cor.latitude}]" />
            </c:when>
            <!-- ELSE -->
            <c:otherwise>
                <c:set var="chaine" value="${chaine},[${cor.longitude},${cor.latitude}]" />
            </c:otherwise>
        </c:choose>
    </c:forEach>