Using JSTL to Create Tables

I am using this JSTL code to create an HTML table. Every other row is assigned a different class, so we can give tables. I know we can do this easily with CSS3, but I have to support older browsers.

Anyway, this is the code I am using - it seems very heavy - is there an easier way to do this?

<c:set var="oddEven" value="true" />
<c:forEach var="row" items="${rows}">
    <c:choose>
        <c:when test="${oddEven}">
        <tr>
        </c:when>

        <c:otherwise>
        <tr class="odd">
        </c:otherwise>
    </c:choose>
            <td>${row.value1}</td>
            <td>${row.value2}</td>
        </tr>
    <c:set var="oddEven" value="${!oddEven}" />
</c:forEach>

      

+2


source to share


3 answers


This should do the trick:

<c:forEach var="row" items="${rows}" varStatus="status">
    <tr
      <c:if test="${status.count % 2 ne 0}">
        class="odd"
      </c:if>
    >
      <td>...</td>
    </tr>
</c:forEach>

      



I am using status.count

in this example; count

counts the number of cycles performed, starting at 1. If you want the count to start at 0, use status.index

.

+3


source


Try



<tr class="${(status.index % 2) == 0 ? 'oddRow' : 'evenRow'}">

      

+1


source


I'm not a JSP guru, but maybe you could write a custom jsp tag for this?

0


source







All Articles