caucho
 Default Attributes with xsl:if


Often, elements should have a default attribute value if none is specified in the XTP file. An <example> tag might have a default CSS class of "example", but let the XTP change the default. In a template, xsl:if will conditionally produce XML depending on an XPath expression.

The following example adds the class attribute to the table depending on the class value in the <box> element. If the XTP file specifies the class, the stylesheet will use it. The the XTP file doesn't specify the class, the stylesheet will use "example" as a default.

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

<xsl:template match="example">
  <table>
    <xsl:attribute name="class">
      <xsl:if test="@class">
        <xsl:value-of select="@class"/>
      </xsl:if>
      <xsl:if test="not(@class)">example</xsl:if>
    </xsl:attribute>
    <tr>
      <td>
        <xsl:apply-templates/>
      </td>
    </tr>
  </table>
</xsl:template>

</xsl:stylesheet>

The example XTP does not specify class, so the stylesheet will use "example" as the default class.

hello.xtp
<example>
This is an example.
</example>

<table class="example">
<tr>
  <td>This is an example</td>
</tr>
</table>

StyleScript

StyleScript's $if uses the test expression for its first argument. If the expression is true, the block is used as a value. If false, the block after the $else will be used for the value.

default.xsl
$template(example) <<
<table>
  $attribute("class") <<
    $if(@class) <<@class>>
    $else <<example>>
  >>
<tr>
  <td>
    $apply-templates();
  </td>
</tr>
</table>
>>

Summary

  • xsl:if evaluates conditionally.
  • not(expr) negates a boolean.

Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark, and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc.