JSP JSTL Using varStatus to Add CSS Class On Last Element

Often when iterating a collection to display it on table specific css class need to be added to the last row for styling purpose, eg:

<tr class="last"><td>Susan</td><td>28</td></tr>

This can be achieved on JSP JSTL core tag by using varStatus attribute:

<c:forEach var="user" items="${users}" varStatus="status">
  <tr ${status.last ? 'class="last"' : ''}>

On varStatus you define what is the variable name which will hold the loop iteration status. This variable then contain information whether or not we’re on the last iteration, and place specific content accordingly. See the javadoc reference for LoopTagStatus for more info.

The question mark and colon syntax ${status.last ? 'class="last"' : ''} is similar to standard Java syntax. It will print the content class="last" only is status.last is true (ie: we’re on the last iteration of loop)


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s