Solstice Coil
Escaping apostrophes for Javascript in XSLT
<a href="#" onclick="showDetails('Waldo','Camouflage expert','Hard to spot, wears a red striped shirt'); return false">Waldo</a>
The problem was that the data coming from my XML file had apostrophes in it, and Javascript doesn't tend to like them inside strings that are already defined by single quotes. But how do you esacpe characters in XSLT? Well, after much googling I'm happy to say I ended up with a viable solution that works quite well.
First, put this in with your other XSLT templates:
<xsl:template name="globalReplace">
<xsl:param name="source"/>
<xsl:param name="from"/>
<xsl:param name="to"/>
<xsl:choose>
<xsl:when test="contains($source,$from)">
<xsl:value-of select=
"concat(substring-before($source,$from),
$to)"/>
<xsl:call-template name="globalReplace">
<xsl:with-param name="source"
select="substring-after($source,$from)"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to"
select="$to"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$source"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Then, populate data like this:
<xsl:variable name="escaped_name">
<xsl:call-template name="globalReplace">
<xsl:with-param name="source" select="Name"/>
<xsl:with-param name="from">'</xsl:with-param>
<xsl:with-param name="to">\'</xsl:with-param>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="escaped_title">
<xsl:call-template name="globalReplace">
<xsl:with-param name="source" select="Title"/>
<xsl:with-param name="from">'</xsl:with-param>
<xsl:with-param name="to">\'</xsl:with-param>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="escaped_description">
<xsl:call-template name="globalReplace">
<xsl:with-param name="source" select="Description"/>
<xsl:with-param name="from">'</xsl:with-param>
<xsl:with-param name="to">\'</xsl:with-param>
</xsl:call-template>
</xsl:variable>
<a href="#" onclick="showDetails('{$escaped_name}','{$escaped_title}','{$escaped_description}'); return false"><xsl:value-of select="Name"/></a>
variable name - of your choice
source - node to be escaped (haystack)
from - character to be replace (needle)
to - character to replace
What this does, essentialy ,is to apply our recursive global replace template to the data in the XML node, and save it in a variable. Then we just pull up the variable using the "value-of" short notation format.
And presto - escaped apostrophe's! (or any other character for that matter).
Hopefully I suffered the headaches of fighting with XSLT so you won't have to. I'm kinda like Jesus, when you come to think about it...
