April 26, 2006

Using conditional special functionality with XSLT imports

Filed under: HowTo, XSLT | Lindsay @ 10:34 am

I solved this problem for someone recently and thought it might be useful to other people in the same situation.

The Problem: how to trigger special functions in a common XSLT file…

There are several XSLT files, one with common functionality shared between all of the others which will be imported into the others. Particular templates in Common.xslt had parts that only needed to be activated if the Common.xslt was imported in specific “host” XSLTs. The problem is that there’s no way to know from Common.xslt whether it should do the special functionality because its unaware of it’s host.

The Soultion: xsl:imports overriding

This can be fixed by exploiting the template overriding property of <xsl:import>. You can create a template in Common.xslt that contains a value you may test for and override it in any of the host XSLT files that need to use that special functionality.

Common.xslt

<xsl:stylesheet version=“1.0″ xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”>
<xsl:output method=“html” version=“4.0″ indent=“no” />

        <xsl:template name=“caller”>common</xsl:template>

        <xsl:template name=“commontemplate”>
                <xsl:variable name=“usespecial”><xsl:call-template name=“caller” /></xsl:variable>
                <xsl:variable name=“whichtype”>
                        <xsl:choose>
                        <xsl:when test=“$usespecial = ’specialfunction’”>special</xsl:when>
                        <xsl:otherwise>normal</xsl:otherwise></xsl:choose>
                </xsl:variable>
                The main XSLT uses <xsl:value-of select=“$whichtype” /> functionality.
        </xsl:template>
</xsl:stylesheet>

SpecialFunction.xslt

<xsl:stylesheet version=“1.0″ xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”>
<xsl:import href=“common.xsl” />
<xsl:output method=“html” version=“4.0″ indent=“no” />

        <xsl:template name=“caller”>specialfunction</xsl:template>
        <xsl:template match=“/”>
                <html><body><xsl:call-template name=“commontemplate” /></body></html>
        </xsl:template>

</xsl:stylesheet>

Results:

<html><body>
The main XSLT uses special functionality.
</body></html>

NormalFunction.xslt
“caller” template is missing…

<xsl:stylesheet version=“1.0″ xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”>
<xsl:import href=“common.xsl” />
<xsl:output method=“html” version=“4.0″ indent=“no” />

        <xsl:template match=“/”>
                <html><body><xsl:call-template name=“commontemplate” /></body></html>
        </xsl:template>

</xsl:stylesheet>

Results:

<html><body>
The main XSLT uses normal functionality.
</body></html>

You can modify this to make as many different types of special functionality as you need.

» » » » » »
, , , , ,