views:

511

answers:

2

I'm using this JSTL code to generate an HTML table. Every other row is given a different class so we can give the table stripes. I know we can do this easily with CSS3 but I have to support old browsers.

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

<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>
A: 

I'm not a JSP guru, but may be you could write a custom jsp tag to do this ?

Pierre
+1  A: 

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 use status.count in this example; count counts the number of times the loop has executed, starting at 1. If you want the counting to start at 0, use status.index.

geowa4