Ashish Sharma
Ashish Sharma

Reputation: 865

Javascript variable = xsl value-of

I am using JavaScript something like this:

<script>
  <xsl:for-each select = '/request/alldata'>

    var l_allDataValue   = '<xsl:value-of select="." />';
    var l_dataArray = l_allDataValue.split('!~');

    callFunction(l_dataArray);

  </xsl:for-each>
</script>

But if there is a apostrophe ' in /request/alldata it will break the JavaScript because the following expression is enclosed in apostrophes:

'<xsl:value-of select="." />'

But it works if I replace this with either of the following...

"<xsl:value-of select="." />" OR "<xsl:value-of select='.' />"

Now I know the apostrophe ' is clashing with the JavaScript code, but which solution will work in all browsers?

Upvotes: 2

Views: 5040

Answers (1)

davmos
davmos

Reputation: 9577

You can use '<xsl:value-of select="." />' but you will need to escape all single quote apostrophes in the <alldata> by prepending a slash like this \'

You can use "<xsl:value-of select="." />" or "<xsl:value-of select='.' />" but if there is a chance the <alldata> will contain a double quote, then you will need to escape those as well, like this \"

If you want to use the first, then this will escape the single quote:

<xsl:template name="escapeSingleQuotes">
  <xsl:param name="txt"/>

  <xsl:variable name="backSlashSingleQuote">&#92;&#39;</xsl:variable>
  <xsl:variable name="singleQuote">&#39;</xsl:variable>

  <xsl:choose>
    <xsl:when test="string-length($txt) = 0">
      <!-- empty string - do nothing -->
    </xsl:when>

    <xsl:when test="contains($txt, $singleQuote)">
      <xsl:value-of disable-output-escaping="yes" 
                    select="concat(substring-before($txt, $singleQuote), $backSlashSingleQuote)"/>

      <xsl:call-template name="escapeSingleQuotes">
        <xsl:with-param name="txt" select="substring-after($txt, $singleQuote)"/>
      </xsl:call-template>
    </xsl:when>

    <xsl:otherwise>
      <xsl:value-of disable-output-escaping="yes" select="$txt"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

You could use in your code like this:

var l_allDataValue = '<xsl:call-template name="escapeSingleQuotes">
                        <xsl:with-param name="txt" select="."/>
                      </xsl:call-template>'

Upvotes: 2

Related Questions