1

Is it possible to handle a parameter to a javascript function in XSLT where the script is between tags <script type=text/javascript>....</script>. If possible could someone give a example. Thanks.

1
  • Do you want to generate <script>...</script> or to call a javascript function during the transformation and use the result of this call further in the transformation? Commented Apr 27, 2012 at 12:21

1 Answer 1

2

I think you're getting confused between the two things: XSLT is something that is used (in this case) to generate HTML/javascript - once that generated HTML/javascript is received by the browser then the javascript can be run. I'm unaware of any such concept of the XSLT "passing" a variable to a javascript function.

My guess is you want something like this XSLT...

<script type="text/javascript">
  var myVar = "<xsl:value-of select="XPATHVALUE"/>";
  <xsl:text disable-output-escaping="yes"><![CDATA[
    function myFunc(){
      alert(myVar);
    }
  ]]></xsl:text>
</script>

If you put the main "body" of the javascript within the xsl:text element, it means you won't get caught out using reserved characters (such as < > etc).

The generated HTML/javascript that is set to the browser would end up as something like this, meaning calling myFunc would display "hello world"...

<script type="text/javascript">
  var myVar = "hello world";
    function myFunc(){
      alert(myVar);
    }
</script>

Update

As MichaelKey has highlighted, the <xsl:text> element above is unnecessary. This should produce the same thing...

<script type="text/javascript">
  var myVar = "<xsl:value-of select="XPATHVALUE"/>";
  <![CDATA[
    function myFunc(){
      alert(myVar);
    }
  ]]>
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

You shouldn't need the disable-output-escaping. The serializer knows it's producing a script element and should handle the content accordingly (if it doesn't, it's a bug).
I didn't realise that. I will give it a go without, but if memory serves me correctly Visual Studio (where I do all my XSLT work) starts showing formatting errors, so I wouldn't have even tried to run it
@MichaelKay As you say, the <xsl:text> element is unnecessary, but you still need to use <![CDATA[..]]> otherwise the translation attempted by .NET does not like reserved characters such as &amp;, &lt; and &gt;
Oops - didn't notice comments don't require escaping... that should be "such as &, < and >"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.