Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML table with alternating row colors via XSL

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.

like image 916
JoelB Avatar asked Jan 22 '09 16:01

JoelB


3 Answers

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.

like image 139
Tomalak Avatar answered Nov 16 '22 03:11

Tomalak


You could also use css3.

tr:nth-child(odd) { background: #ff0000; }

Supported as of IE9 an for quite some time by all the other browsers.

like image 35
Gerben Avatar answered Nov 16 '22 03:11

Gerben


Use an XSL:When and compare position mod 2 to get odd or even rows to alter classes when needed like:

<xsl:choose>
    <xsl:when test="position() mod 2 = 1">
        <td class="odds">blah</td>
    </xsl:when>
    <xsl:otherwise>
        <td class="even">blah</td>
    </xsl:otherwise>
</xsl:choose>

EDIT: Getting my odd/even the right way around sigh

like image 34
Wolfwyrd Avatar answered Nov 16 '22 01:11

Wolfwyrd