2013-03-25 39 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