January 8, 2002 - Conditional Coloring in XSLT | WebReference

January 8, 2002 - Conditional Coloring in XSLT

Yehuda Shiran January 8, 2002
Conditional Coloring in XSLT
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

The <xsl:choose> element provides a mechanism for either/or processing. The <xsl:choose> element contains a series of <xsl:when> elements that are tested in order, from top to bottom, until a match is found. An <xsl:otherwise> element can be used to insert a template if no match is found.

The following code can color-code rows in a report card, by grade. 0-55 are displayed in red, 55-80 are displayed in yellow, and 80-100 are displayed in green. The color is changed by generating a portion of the STYLE attribute value (the color property). Notice that once a record is matched, it is not tested again down the list. That's why we can test for grades less than 56, and then test for grades less than 81. Records matching the first test (less than 56) will be colored red, then records matching the second test (less than 81) will be colored yellow. But the red records (less than 56) will not be colored again, with yellow. Once they were colored (with red), they are not tested anymore.

<TR>
  <xsl:attribute name="STYLE">color:
    <xsl:choose>
      <xsl:when test="score[. < 56]">red</xsl:when>
      <xsl:when test="score[. < 81]">yellow</xsl:when>
      <xsl:otherwise>green</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</TR>