SVG Utility

The SVG utility is designed to help you to embed the SVG images that you generate using XSLT into an HTML page.

Creating SVG with XSLT is very cool. Unfortunately, it's difficult to generate HTML pages that use SVG because the embed elements that are used to host SVG refer to separate files rather than allowing SVG within them. However, you can get around this by loading the SVG into the embed through a script, using Chris Bayes' domtodom.js.

The crucial insight of this utility was the fact that the loading of the SVG images into the embed elements can be triggered by a script in a static SVG image. This utility creates the script and the embed elements for the page.

Instructions

  1. Download svg-utils.zip and unzip it into the same directory as your stylesheet. It contains three files:
  2. Import the svg-utils.xsl stylesheet into your stylesheet:

    <xsl:import href="svg-utils.xsl" />
  3. Create a variable holding a node set within which each node represents a separate image to be placed in the document (I call these image nodes).

    <xsl:variable name="images" select="document('')/*/my:diagrams/my:diagram" />
  4. Within the head element of the HTML, call the template 'insertSVGScript' with the images parameter being the node set of image nodes:

    <head>
       <title>SVG Chart Demonstration</title>
       <xsl:call-template name="insertSVGScript">
          <xsl:with-param name="images" select="$images" />
       </xsl:call-template>
    </head>
  5. Add templates in 'getSVG' mode that match the image nodes. These templates should return SVG images.

    <xsl:template match="my:diagram" mode="getSVG">
       ...
       <svg width="100%" viewBox="0 0 {$width} {$height}" preserveAspectRatio="xMinYMin meet">
          ...
       </svg>
    </xsl:template>
    
  6. Apply templates to the image nodes in 'createEmbed' mode to create embed elements for the at the relevant points in the HTML.

    <xsl:apply-templates select="$images" mode="createEmbed" />
    

There are a few extra options that you can set as parameters for the 'createEmbed' template, namely:

$src [= 'blank.svg']
The name of the blank SVG file to be used in place while the SVG images are loaded. These should all contain a call to the function triggerSVGLoading(). Have a look at the source of blank.svg for an example.
$width
The desired width of the embed.
$height
The desired height of the embed.

More Information


/xslt/utilities/svg-utils.xml by Jeni Tennison; generated using SAXON 6.5 from Michael Kay