XSL Tips - Using Mod to Alternate Color

William Pohlhaus' Web Site

Home > XSL Tips > Using Mod to Alternate Color


Side Links
Home
Resume
Jennifer (wedding picutes)
Seda (baby pictures)
Java
Presentation
XSL Tips
My Other Homepage (Dust Boy)
 
Mod Color
  This is a simple example of using xsl:if and postion() to alternate color in an html table. Nothing special but useful if displaying lots of xml information in a html format using tables.
XML
<top>
  <books>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
    <book>test</book>
  </books>
</top>

XSL
 <?xml version="1.0" encoding="US-ASCII" ?>

  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">


    <xsl:template match="top">
      <table>
        <xsl:apply-templates select="books"/>
      </table>
    </xsl:template>


    <xsl:template match="books">
      <xsl:for-each select="book">
        <tr>
          <xsl:if test="position() mod 2 = 1">
            <td bgcolor="#aaaaaa">
              <xsl:value-of select="position()" />
              <xsl:value-of select="."/>
            </td>
          </xsl:if> 
          <xsl:if test="position() mod 2 = 0">
            <td bgcolor="#aaaaff">
              <xsl:value-of select="position()" />
              <xsl:value-of select="."/>
            </td>
          </xsl:if>

      </tr>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>
Result
1 test
2 test
3 test
4 test
5 test
6 test
7 test
8 test
9 test