7.4 Invoking Templates with Parameters

The with-param.xsl stylesheet shown in Example 7-1 doesn't define a global parameter on the top level, but it does define a local variable within a template.

Example 7-1. A stylesheet using a locally scoped variable
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:output doctype-system="catalog.dtd"/>     <xsl:template match="catalog">  <xsl:copy>   <xsl:apply-templates select="item">    <xsl:with-param name="discount" select="'0.50'"/>   </xsl:apply-templates>  </xsl:copy> </xsl:template>     <xsl:template match="item">  <xsl:param name="discount"/>  <xsl:copy>   <xsl:attribute name="id"><xsl:value-of select="@id"/></xsl:attribute>   <xsl:copy-of select="maker|description|size|price"/>   <discount><xsl:value-of select="$discount"/></discount>   <discountPrice><xsl:value-of select="price - (price * $discount)"/></discountPrice>   <xsl:copy-of select="currency"/>  </xsl:copy> </xsl:template>     </xsl:stylesheet>

The first child element of the template that matches item is the param element, which just happens to be empty by default. When you use local parameters defined with param, the param element must appear as the first child element in a template. This was probably so that their values are taken into account before the template is processed. You can also define local variables in a template with the variable element, but these can appear anywhere in a template. They don't have to be first in line.

The template that matches catalog applies templates to item elements, but as it does so, it adds a child to apply-templates called with-param. This element passes a new value for the local discount parameter to the template that matches item. To see how it works, enter the following line at a prompt:

xalan -i 1 price.xml with-param.xsl

The processor yields the following deeply discounted results:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog>  <item >   <maker>Scratchmore</maker>   <description>Wool sweater</description>   <size>L</size>   <price>120.00</price>   <discount>0.50</discount>   <discountPrice>60</discountPrice>   <currency>USD</currency>  </item> </catalog>

You can use the with-param element in two places, either as a child of apply-templates or as a child of call-template. You will see how you can use with-param with call-template in Chapter 10.

In XSLT 1.0, parameters are not passed through by built-in templates. XSLT 2.0, however, does pass through parameters via built-in templates.


In the final examples in this chapter, I'll show you how to create a variable value with a result tree fragment, and then how to use that fragment later in the stylesheet.



Learning XSLT
Learning XSLT
ISBN: 0596003277
EAN: 2147483647
Year: 2003
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net