Re: [xsl] javascript variable in XSLT

Subject: Re: [xsl] javascript variable in XSLT
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Thu, 21 Nov 2002 12:19:02 +0000
Hi Stevenson,

> how can i set a javascript variable in an xsl variable. i.e. if
> 'iSend' is a javascript variable already available in an xsl file,
> how do i set it in an xsl file?
>
> am thinking of using <xsl:variable name="send" select="iSend"> but i
> don't think it's right.

What do you mean when you say that 'iSend' is "already available in an
xsl file"? There are two ways in which JavaScript code can appear in a
stylesheet:

1. The JavaScript is generated using XSLT. In this case, the
JavaScript is treated as plain text by the XSLT processor. It doesn't
know what a JavaScript variable is. You can generate JavaScript in
which the value of a variable is set to the value of an XSLT variable
using, for example:

  <script type="text/javascript">
    ...
    iSend = <xsl:value-of select="$send" />;
    ...
  </script>

Assuming $send has the value 4, this generates, in the (HTML, say)
output:

  <script type="text/javascript">
    ...
    iSend = 4;
    ...
  </script>

When the HTML is viewed and the <script> element interpreted by an
HTML browser then the JavaScript is interpreted and the iSend variable
set to the value 4.

2. The JavaScript is used inside a <msxsl:script> element (or
somewhere similar). In this case, the XSLT processor is a JavaScript
processor as well, but the scope of the JavaScript is limited to the
<msxsl:script> element and the function definitions defined therein.
The usual way to get/set JavaScript variables in this context is to
create get/set functions that change the value of the variable:

<msxsl:script language="javascript" implements-prefix="my">
  var iSend;

  function setISend(send) {
    iSend = send;
  }

  function getISend() {
    return iSend;
  }
</msxsl:script>

Then you can use:

  <xsl:value-of select="my:getISend()" />

to output the value of the JavaScript iSend variable and:

  <xsl:variable name="temp" select="setISend(4)" />

to set the value of the JavaScript iSend variable to 4.

Mixing JavaScript and XSLT code like this is a really bad idea,
particularly because it violates the principle of "no side-effects"
and therefore prevents your processor from doing certain
optimisations or leads to unanticipated results.

I suggest that you describe what you're trying to do, with examples
from your stylesheet and the result that you're trying to generate,
and we might be able to help you find another way to do it.

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread