James Ives
James Ives

Reputation: 3365

Using arrays with JSP

I have two objects that I want to combine into a single variable. The objects look like so

{name: "James", type: "author"}, {name: "Amelia", type: "author"}

And they can be accessed via ${global.content.credits.by} in my JSP. What I would to do is have the two names from each object listed out so they look like: James, Amy (without a trailing comma for the last item in the list) when the ${authorNames} variable is called.

I've tried the following:

<c:forEach items="${global.content.credits.by}" var="author" varStatus="loop">
   <c:set var="authorNames" value="${author.name}" />
</c:forEach>

But the only way I can get all of the author names to show is within the loop, outside of the loop the ${authorNames} variable gets overwritten on each iteration.

Is there some sort of array push method in JSP I can use to combine both names, and then add a comma between each one besides the last one in the loop.

Upvotes: 1

Views: 56

Answers (1)

GriffeyDog
GriffeyDog

Reputation: 8386

You can append the names to authorNames, instead of overwriting it.

<c:forEach items="${global.content.credits.by}" var="author" varStatus="loop">
   <c:if test="${loop.index == 0}>
     <c:set var="authorNames" value="${author.name}" />
   </c:if>
   <c:if test="${loop.index != 0}>
     <c:set var="authorNames" value="${authorNames},${author.name}" />
   </c:if>
</c:forEach>

Upvotes: 2

Related Questions