XSL allows you to define variables and refer to them with the same dollar-sign ($) notation found in Perl and PHP. However, these variables have some unusual constraints. For example, once defined, their values cannot be changed.
<xsl:variable name="var" select="'Hello world!'" /> <xsl:value-of select="$var" />
The output of this XSL will be the string, "Hello world!" Although they lack the power of the variables found in programming languages, XSL's variables are very useful for creating compact references to complex XPath designations.
Variables are also behind the parameters that XSL allows you to pass to templates.
<xsl:template name="example">
<xsl:param name="$p" select="1" />
<xsl:choose>
<xsl:when test="$p=1">Hello, world!</xsl:when>
<xsl:otherwise>Goodbye, cruel world!</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:call-template name="example" />
<br />
<xsl:call-template name="example">
<xsl:with-param name="p" select="1" />
</xsl:call-template>
<br />
<xsl:call-template name="example">
<xsl:with-param name="p" select="0" />
</xsl:call-template>
The output of this is the following:
Hello, world! Hello, world! Goodbye, cruel world!
In the first case, no value is passed as the parameter, so the default value of "1" is used. In the second case, the default value of "1" is passed explicitly. In the third case, a different value, "0", is passed. These different values change the functionality of the template, allowing one template to produce slightly different output in different circumstances.
To proceed with this tutorial, click XSL Tips.