Passing Parameters

Contact Us or call 1-877-932-8228
Passing Parameters

Passing Parameters

XSLT templates can accept parameters, which can be passed from xsl:apply-templates and xsl:call-template. The following code illustrates this.

Code Sample:

TemplatesParametersVariables/Demos/BeatlesCallTemplates2.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:template match="/">
		<xsl:call-template name="StartHTML">
			<xsl:with-param name="Title" select="'Beatles'"/>
		</xsl:call-template>
	</xsl:template>
	<xsl:template name="StartHTML">
		<xsl:param name="Title" select="'Untitled'"/>
		<html>
			<head>
				<title><xsl:value-of select="$Title"/></title>
			</head>
			<body>
				<h1><xsl:value-of select="$Title"/></h1>
				<ul>
					<xsl:apply-templates select="beatles/beatle">
						<xsl:sort select="lastname"/>
					</xsl:apply-templates>
				</ul>
			</body>
		</html>
	</xsl:template>
	<xsl:template match="beatle[not(@real='no')]">
		<li style="color:blue;"><xsl:apply-templates/></li>
	</xsl:template>
	<xsl:template match="beatle">
		<li style="color:red; text-decoration:line-through">
			<xsl:apply-templates/>
		</li>
	</xsl:template>
	<xsl:template match="name">
		<xsl:value-of select="lastname"/>,
		<xsl:value-of select="firstname"/>
	</xsl:template>
</xsl:stylesheet>

The xsl:call-template element looks like this:

<xsl:call-template name="StartHTML"> <xsl:with-param name="Title" select="'Beatles'"/> </xsl:call-template>

The nested xsl:with-param element is used to pass a value for Title to the StartHTML template, which looks like this:

<xsl:template name="StartHTML"> <xsl:param name="Title" select="'Untitled'"/> <html> <head> <title><xsl:value-of select="$Title"/></title> </head> <body> <h1><xsl:value-of select="$Title"/></h1> <ul> <xsl:apply-templates select="beatles/beatle"> <xsl:sort select="lastname"/> </xsl:apply-templates> </ul> </body> </html> </xsl:template>

The xsl:param element is used to receive the value passed in. Notice that the names used in the xsl:with-param and in the xsl:param elements are the same. This is required as multiple parameters could be passed in with different names.

This xsl:param element also has a select attribute. This is the default value in the event that no value for Title is passed in.

The Title parameter is referenced twice, once in the HTML title element and once in the HTML h1 element. Notice that it is preceded by a dollar sign ($) when referenced. This tells the XSLT processor that it is variable rather than an XPath.

Another thing to notice is that xsl:with-param is passing in a literal string for Title. Notice the single quotes around Beatles in select="'Beatles'". It could just as easily pass in an XPath if the title were to be dynamically retrieved from the XML source document.

Next