Search code examples
xmlxsltimportstylesheet

How do I import templates from another stylesheet?


I know I have to use the xsl:import but I don't know how do I call the name of the templates.

How do I do it?


Solution

  • Using <xsl:import> applying <xsl:call-template> is quite easy:

    Sample XML named f.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        <a>abc</a>
        <b>cde</b>
    </root>
    

    Main sample XSLT f.xslt:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:import href="f1.xslt"/>
    
     <xsl:template match="/root">
       A: <xsl:value-of select="a/text()" />
       <xsl:call-template name="secondTemplate" />
     </xsl:template>
    
    </xsl:stylesheet> 
    

    Include sample XSLT f1.xslt:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
     <xsl:template name="secondTemplate">
       B: <xsl:value-of select="b/text()" />
     </xsl:template>
    
    </xsl:stylesheet> 
    

    Output:

    <?xml version="1.0"?>
    
       A: abc
       B: cde
    

    So the first XSLT(f.xslt) does call the second XSLT(f1.xslt) - which is imported with <xsl:import ...> - via a named template which is accessed with the <xsl:call-template name="secondTemplate" /> line.