JoelB
JoelB

Reputation: 349

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.

Upvotes: 17

Views: 26335

Answers (4)

Tomalak
Tomalak

Reputation: 338238

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.

Upvotes: 40

Gerben
Gerben

Reputation: 16825

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.

Upvotes: 4

Juan Zamora
Juan Zamora

Reputation: 386

May we want to change only the class name instead, when can choose inside a variable to enable change its inner value. Something like this:

<xsl:variable name="myDemoClass" >
   <xsl:choose>
     <xsl:when test="position() mod 2 = 0">
       <xsl:text>myDemoClass</xsl:text>
     </xsl:when>
     <xsl:otherwise>
       <xsl:text>myDemoClass otherClass</xsl:text>
     </xsl:otherwise>
   </xsl:choose>
</xsl:variable>

With this, we are able to change the variable name and then we can change for example, a div class content.

<div class="{$myDemoClass}">

Regards!

Upvotes: 1

Wolfwyrd
Wolfwyrd

Reputation: 15916

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

Upvotes: 1

Related Questions