Friday, June 20, 2008

XSLT - javascript escaping

I could not find a way to do this without writing a template.
I started one then luckily through the power of the Internet found a better one.  Done by Jeni Tennison found in the xsl-list archives and I have reproduce here.

<xsl:template name="escape-javascript">
<xsl:param name="string" />
<xsl:choose>
<xsl:when test='contains($string, "&apos;")'>
<xsl:call-template name="escape-javascript">
<xsl:with-param name="string"
select
='substring-before($string, "&apos;")' />
</xsl:call-template>
<xsl:text>\'</xsl:text>
<xsl:call-template name="escape-javascript">
<xsl:with-param name="string"
select
='substring-after($string, "&apos;")' />
</xsl:call-template>
</xsl:when>
<xsl:when test="contains($string, '&#xA;')">
<xsl:call-template name="escape-javascript">
<xsl:with-param name="string"
select
="substring-before($string, '&#xA;')" />
</xsl:call-template>
<xsl:text>\n</xsl:text>
<xsl:call-template name="escape-javascript">
<xsl:with-param name="string"
select
="substring-after($string, '&#xA;')" />
</xsl:call-template>
</xsl:when>
<xsl:when test="contains($string, '\')">
<xsl:value-of select="substring-before($string, '\')" />
<xsl:text>\\</xsl:text>
<xsl:call-template name="escape-javascript">
<xsl:with-param name="string"
select
="substring-after($string, '\')" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$string" /></xsl:otherwise>
</xsl:choose>
</xsl:template>

No comments: