How to access global variable value in multiple te

2019-08-07 11:16发布

I have created a global variable and its been used in two templates I am able to access i first template, not able to get the value in second template . Below are my workings

 <xsl:variable name="currentValue"></xsl:variable> //global variable declaration

  <xsl:template match="/">
  <xsl:variable name="unique-accounts" select="/*/*/*/accountId/text()generate-id()=generate-id(key('account-by-id', .)[1])]"/>
 <xsl:for-each select="$unique-accounts">
      <xsl:variable name="currentValue" select="current()"/>
       <xsl:value-of select="$currentValue"/> //here value is printing
       <xsl:apply-templates select="//secondTemplate"/>
 </xsl:for-each>
 </xsl:template> //close od first template

<xsl:template match="secondTemplate"> 
  <xsl:value-of select="$currentValue"/>  //here value is not printing
</xsl:template>

标签: xslt
2条回答
Lonely孤独者°
2楼-- · 2019-08-07 11:45

Variables in XSLT are named values, they are not memory locations in which you can place different values at different times. That's a fundamental difference between declarative and procedural programming.

If you would like to explain the problem you are trying to solve (that is, the input and output of the transformation) then I'm sure we can explain how to write it in XSLT. Reverse-engineering the requirement from a completely wrong approach to the solution isn't possible.

查看更多
男人必须洒脱
3楼-- · 2019-08-07 11:58

If I follow the logic of your code correctly (which is not at all certain), you have declared a global variable as:

<xsl:variable name="currentValue"></xsl:variable>

i.e. as empty. You are then calling this global variable inside your second template:

<xsl:template match="secondTemplate"> 
  <xsl:value-of select="$currentValue"/>
</xsl:template>

and getting an empty result - which is exactly what you should expect.

Within your first template, the declaration:

<xsl:variable name="currentValue" select="current()"/>

overrides the global variable declaration for the scope of the template (more precisely, for the following siblings of the declaration and their descendants - but since the declaration is the first thing you do in the template, it comes down to the same thing).

In more technical terms, the binding established within the template shadows the binding established by the top-level xsl:variable element:
http://www.w3.org/TR/xslt/#dt-shadows

查看更多
登录 后发表回答