2012-03-30 70 views
17

在XSLT 1.0中,將當前上下文節點傳遞給被調用模板並使該節點成爲被調用模板內的上下文節點的最短/最簡潔/推薦的方式是什麼?XSLT在調用模板中傳遞當前上下文

如果一個沒有xsl:param並且被一個空的調用模板調用的模板會簡單地拿起調用者的上下文節點,那麼它會很好(它會是吧?),但我能想到的最好的是:

<xsl:call-template name="sub"> 
     <xsl:with-param name="context" select="." /> 
    </xsl:call-template> 

<xsl:template name="sub"> 
    <xsl:param name="context" /> 
    <xsl:for-each select="$context"> 

    </xsl:for-each> 
</xsl:template> 

回答

22

這將是很好(它會吧?)如果沒有xsl:param 和空call-template稱爲模板將只需拿起 調用者的上下文節點。

這是xsl:call-template究竟是如何在W3C XSLT 1.0(2.0)規範所定義,並且由任何符合XSLT處理器實現。

這裏是一個小例子:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text"/> 

<xsl:template match="a"> 
    <xsl:call-template name="currentName"/> 
</xsl:template> 

<xsl:template name="currentName"> 
    Name: <xsl:value-of select="name(.)"/> 
</xsl:template> 
</xsl:stylesheet> 

當在下面的XML文檔施加這種轉變:

<t> 
<a/> 
</t> 

有用,正確的結果產生

Name: a 
+0

謝謝迪米特雷。我沒有看到這個記錄,當我嘗試它時似乎沒有工作。我沒有找到正確的地方,一定是在做別的事情。 +1 Q回答。乾杯。 – JPM 2012-03-30 13:37:33

+0

@JPM:不客氣。您可能一直在研究XSLT 2.0中的'xsl:function'指令 - 它與命名模板不同,因爲它沒有收到函數調用者的上下文,並且如果調用者必須通過它的上下文節點作爲參數,如果這個上下文節點必須被傳遞。 – 2012-03-30 13:56:57

4

解釋Dimitre所說的內容。

當您從一個節點調用模板,你就已經存在於該節點,

例如:

假定這段代碼:

<xsl:template match="MyElement"> 
    <xsl:call-template name="XYZ"/> 
</xsl:template> 

<xsl:template name="XYZ> 
    <xsl:value-of select="."/> 
</xsl> 

上面的代碼寫作一樣好:

<xsl:template match="MyElement"> 
    <xsl:value-of select="."/> 
</xsl:template> 

您也可以在被調用的模板中使用for-each循環。 :)

但只是要確定你到底在哪裏..