Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to iterate two items simultaneously using foreach in jstl?

I have two items from my model and I want to iterate them at the same using jstl foreach. how can I achieve this using a correct syntax?

like image 348
randy Avatar asked Nov 10 '10 08:11

randy


People also ask

How to iterate array in JSTL?

Iterating over array using JSTL forEach loop For iterating over an array e.g. String array or integer array in JSP page, "items" attribute must resolved to an array. You can use expression language to get an Array stored in of scope available in JSP e.g. page scope, request scope, session or application scope.

What is varStatus in forEach of JSTL?

varStatus is what you want! You declare a new variable within the main forEach JSP block which will allow you to access the internal loop counter of the for-each loop. Then you can call a number of methods on that object to be able to do conditional processing.

Which JSTL tag would you use to iterate over a collection of objects?

These tag used as a good alternative for embedding a Java while, do-while, or for loop via a scriptlet. The < c:for each > tag is most commonly used tag because it iterates over a collection of object.


1 Answers

You can call varStatus.index to get the index of the current round of iteration, and then use it as a lookup for the second list.

For example, if you have two lists people.firstnames and people.lastnames you can do:

<c:forEach var="p" items="${people.firstnames}" varStatus="status">
  <tr>
      <td>${p}</td>
      <td>${people.lastnames[status.index]}</td>
  </tr>
</c:forEach>
like image 187
dogbane Avatar answered Oct 24 '22 03:10

dogbane