2013-03-25 44 views
0

我有一个XSL它看起来像:如何在XSL-循环改变变量值

<xsl:param name="relativeURL"/> 
<xsl:param name="isPersonalPage" /> 
<xsl:template match="/"> 
    <xsl:call-template name="main_level" > 
     <xsl:with-param name="urlMatched" select="siteMap/siteMapNode/siteMapNode/@url= $relativeURL" /> 
    </xsl:call-template> 
</xsl:template> 

<xsl:template name="main_level" match="/"> 
<div> 
<xsl:param name="urlMatched" /> 
     <xsl:for-each select="siteMap/siteMapNode/siteMapNode"> 
       <xsl:choose> 
       <xsl:when test="(@url = $relativeURL)"> 
        <a class="top_link active"> 
         <xsl:attribute name="href"> 
          <xsl:value-of select="@url"/> 
         </xsl:attribute> 
          <xsl:value-of select="@topNavTitle"/> 
        </a> 
       </xsl:when> 
       <xsl:otherwise> 
          <xsl:choose> 
          <xsl:when test="($isPersonalPage = 'true') and (!($urlMatched))"> 
           <a class="top_link active"> 
            <xsl:attribute name="href"> 
             <xsl:value-of select="@url"/> 
            </xsl:attribute> 
            <xsl:value-of select="@topNavTitle"/> 
           </a> 
          </xsl:when> 
          <xsl:otherwise> 
           <a class="top_link"> 
           <xsl:attribute name="href"> 
            <xsl:value-of select="@url"/> 
           </xsl:attribute>  
           <xsl:value-of select="@topNavTitle"/>   
           </a> 
          </xsl:otherwise> 
          </xsl:choose> 
       </xsl:otherwise> 
       </xsl:choose> 
     </xsl:for-each> 
</xsl:template> 

所以,基本上我需要遍历节点,并看看是否有任何节点的url属性有相匹配特定的URL。如果这样,将变量的值设置为别的东西。然后在被调用的模板“main_nav”中,我希望根据“urlMatched”变量的值进行操作。 但我不确定我是否可以在两者之间改变一个变量的值。任何人都可以帮我解决这个问题吗?

回答

0

这不需要for-each,因为当一边是节点集时等于测试工作的方式。只要

<xsl:variable name="urlMatched" 
    select="siteMap/siteMapNode/siteMapNode/@url = $relativeUrl" /> 

会做你需要什么,仿佛任何在左侧的一组节点的右边的值相匹配,否则为false表达式为true。您应该可以稍后使用<xsl:if test="$urlMatched">来测试此值。

至于使用其他模板的值,请记住,在XSLT的变量都是局部 - 你将需要传递一个参数,如果你想在另一个模板

<xsl:template name="something"> 
    <xsl:param name="urlMatched" /> 
    <!-- template body here --> 
</xsl:template> 

... 
    <xsl:call-template name="something"> 
    <xsl:with-param name="urlMatched" 
    select="siteMap/siteMapNode/siteMapNode/@url = $relativeUrl" /> 
    </xsl:call-template> 

或者只是做使用的值在被调用的模板而不是调用者中进行计算,因为call-template不会更改上下文,因此同一个选择表达式也可以在那里工作。

+0

什么将我的变量包括如果发现或没有找到relativeUrl?因为我需要稍后检查这个值,并根据它进行一些编码。 – 2013-03-25 09:39:13

+0

@RossCooper我已经添加了一些可以帮助你的信息。 – 2013-03-25 09:55:46

+0

嗨伊恩,我用我现在使用的实际代码更新了问题。我仍然没有得到所需的输出。相反,我得到一个500错误。 :( – 2013-03-25 10:21:27

1

请记住,变量在XSLT中是只读的。也就是说,你可以只分配一次。之后,它们是只读的。

请参阅此相关的问题

update the variable in xslt

+0

什么是替代方案。我无法理解你给出的链接中的一件事。我认为这种情况并不存在类似于我的情况。 – 2013-03-25 10:02:58

+0

您无法更新循环中的变量。您只能分配一次变量。之后是只读的。如果你尝试更新它,你会得到一个运行时错误。 – Luixv 2013-03-25 10:22:51