Javascript in Xslt

by on under web
1 minute read

Sometimes you want to add just a little bit of javascript action to your html outputs of your xslt conversion scripts. The simplest way, the recommended way if you can afford it, is to go with a separate javascript file and use it this way:

<script type="text/javascript" src="file.js">
  &#160;
</script> 

However, if you are unable to do it this way and you have to include the code directly in a <script> tag, then you have to make it work some other way. Your first try might be:

<script type="text/javascript">
  console.log("How you doin'?");
</script> 

And this works. How nice. Let’s make the code contain some characters, that xslt treats differently then other characters. I chose <

<script type="text/javascript">
  if(1 < 2) console.log("How you doin'?");
</script> 

The xslt processor 1 will try to decode the < character as a start of a tag. Which gives us this error:

main.xslt:7: parser error : StartTag: invalid element name
            if(1 < 2) console.log("How you doin'?");
                  ^
cannot parse main.xslt

Let’s fix this by using a CDATA section:

<script type="text/javascript">
  <![CDATA[ 
  if(1 < 2) console.log("How you doin'?"); 
  ]]>
</script> 

And the transformation works 2. However, let’s take a look at the output:

<script type="text/javascript">
   if(1 &lt; 2) console.log("How you doin'?"); 
</script>

The < character was escaped and we do not want that. Luckily, the xsl:text element contains disable-output-escaping attribute, that handles this. Use it like so:

<script type="text/javascript">
  <xsl:text disable-output-escaping="yes">
    <![CDATA[ 
      if(1 < 2) console.log(":)"); 
    ]]>
  </xsl:text>
</script>

And this is how I was able to use all of my javascript code without any errors. So far…

1: For this post I was using libxml 20909, libxslt 10133-GITv1.1.33 and libexslt 820.
2: This actually works differently on libxslt’s transform compared to XSLTProcessor in the browser.

xslt, javascript
invisible image loader