Alex Rivera | Logout

HTML table with alternating row colors via XSL

Asked 2009-01-22T16:51:16.020
17

What is the easiest way to alternate row colors in an HTML table (a.ka. striping). Most of my tables are created in XSL templates like the following, with the table, thead, etc.. defined in another template.

<xsl:template match="typ:info">
  <tr>
    <td>
      <xsl:value-of select="typ:dateAccessed" />
    </td>
    <td>
      <xsl:value-of select="typ:loginId" />
    </td>
  </tr>
</xsl:template>

My preference is to use alternating classes on the elements.

Edit
Report

1 Answer

40

If you must produce hard-coded colors in HTML:

<xsl:template match="typ:info">
  <xsl:variable name="css-class">
    <xsl:choose>
      <xsl:when test="position() mod 2 = 0">even</xsl:when>
      <xsl:otherwise>odd</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <tr class="{$css-class}">
    <td>
      <xsl:value-of select="typ:dateAccessed" />
    </td>
    <td>
      <xsl:value-of select="typ:loginId" />
    </td>
  </tr>
</xsl:template>

With today's browsers you are much better off using CSS and tr:nth-child(odd).

This results in less hassle on the XSLT side, much cleaner HTML markup - and it's compatible with client-side table sorting and -filtering.

answered 2009-01-22T17:01:53.813

Your Answer