2012-06-30 71 views
5

如何在XSLT中的两个模板之间传递变量。如何在XSLT中的两个模板之间传递变量

我不能使用全局变量,因为变量的值取决于当前正在评估的节点。

说我有几分XSLT:

<xsl:template match="product"> 
<xsl:variable name="pr-pos" select="count(./preceding-sibling::product)+1"/> 
.. 
.. 
.. 
<xsl:apply-templates select="countries/country"/> 
</xsl:template> 

<xsl:template match="countries/country"> 
<tr id="country-id"> 
    <td><a href="#" class="action" id="{concat('a-',$pr-pos)}">+</a></td> 
.. 
.. 

这给了错误的$ PR-pos是不是第二个模板访问。

如何将变量pr-pos的值传递给其他模板?我怎样才能做到这一点?

+0

在你的情况下,你并不需要传递一个变量。您希望通过的'$ pr-pos'的值可以从'country'模板中辨别。 – Utkanos

+0

所有编程语言(大多数)都有一种方法将信息传递给另一个执行单元,并学习如何做到这一点是基本原则之一。这个问题大致相当于问如何在JavaScript中的两个函数之间传递变量,或者说“我试过'函数a(){var i = 5; b();} function b(){alert(i); }'但是'i'在第二个函数中不可访问。“ – 2012-07-01 08:23:00

+0

@torazaburo:我找不到一个有用的东西,它告诉我如何在google上做到这一点。我不知道这就是为什么问,如果你有问题的人问你为什么不在StackOverflow上禁用你的帐户。搜索谷歌,并告诉我你找到除了W3文档以外的任何好文档。 – Harshdeep

回答

10
<xsl:template match="product"> 
    <xsl:variable name="pr-pos" select="count(./preceding-sibling::product)+1"/> 
    .. 
    .. 
    .. 
    <xsl:apply-templates select="countries/country"> 
     <xsl:with-param name="pr-pos" select="$pr-pos" /> 
    </xsl:apply-templates> 
</xsl:template> 

<xsl:template match="countries/country"> 
    <xsl:param name="pr-pos" /> 
    <tr id="country-id"> 
     <td><a href="#" class="action" id="{concat('a-',$pr-pos)}">+</a></td> 
     .. 
     .. 
+0

我搜索了一些,并做了完全相同的事情,然后检查StackOverflow上的答案,它工作。然后也感谢您的帮助:) – Harshdeep