Combining Multiple Stylesheets

Through template parameters, named templates, and template modes, we have seen how to create more reusable fragments of code that begin to resemble function calls. By combining multiple stylesheets, one can begin to develop libraries of reusable XSLT templates that can dramatically increase productivity.

Productivity gains occur because programmers are not writing the same code over and over for each stylesheet. Reusable code is placed into a single stylesheet and imported or included into other stylesheets. Another advantage of this technique is maintainability. XSLT syntax can get ugly, and modularizing code into small fragments can greatly enhance readability. For example, we have seen several examples related to the list of presidents so far. Since we almost always want to display the name of a president or vice president, name-formatting templates should be broken out into a separate stylesheet. Example 3-7 shows a stylesheet designed for reuse by other stylesheets.

Example 3-7. nameFormatting.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html"/>
  <!--
    ** Show a name formatted like: "Burke, Eric Matthew"
    -->
  <xsl:template match="name" mode="lastFirstMiddle"> <xsl:value-of select="last"/> <xsl:text>, </xsl:text> <xsl:value-of select="first"/> <xsl:for-each select="middle"> <xsl:text> disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:value-of ...

Get Java and XSLT now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.