2012-08-13 22 views
1

多次我有一個像下面使用相同的XSLT代碼在同一個文件

<xsl:choose> 
     <xsl:when test="v:Values = 'true'"> 
     <xsl:text>A</xsl:text> 
     </xsl:when> 
     <xsl:otherwise> 
     <xsl:text>B</xsl:text> 
     </xsl:otherwise> 
... 
    </xsl:choose> 

一些XSLT代碼我想使用的代碼,很多時候,這一塊在同一個文件。我可以將它放在模板中並在需要時調用它嗎?

+1

http://www.webmasterworld.com/xml/3295698.htm。在頁面的一半處查看。 – 2012-08-13 21:46:26

回答

2

是 - 它被稱爲xsl:call-template。

任何模板都可以被命名。該名稱可以通過名稱空間進行限定。例如...

<xsl:template match="some match condition" name="call-me"> 
    bla bla bla (template content) 
</xsl:template> 

如果模板都有一個名字,它甚至可以省略匹配條件是這樣的...

<xsl:template name="call-me"> 
<xsl:param name="phone-number" /> 
    bla bla bla (template content) 
</xsl:template> 

命名的模板有許多參數,只要你喜歡。以上片段是聲明一個名爲phone-number的參數的示例。在模板的順序構造,你會參考這個參數,以同樣的方式作爲一個變量,像這樣......

$phone-number 

要調用一個命名模板,使用XSL:從序列中調用模板構造函數。例如...

<xsl:call-template name="call-me"> 
<xsl:with-param name="phone-number" select="'55512345678'" /> 
</xsl:template> 

請注意,xsl:with-param用於傳遞實際參數值。

請注意,在XSLT 2.0中,您還可以定義可從XPATH表達式中調用的函數。在某些情況下,函數可能是命名模板的更好選擇。

參見:

  1. XSLT 2.0 spec re.: named templates
  2. XSLT 1.0 spec re.: named templates
+0

@Filburt感謝您的糾正。 – 2012-08-14 06:10:03

+0

有沒有辦法在調用模板時更改上下文節點?這是必要的,因爲在模板內部,我只使用相對xpath。 – daniely 2012-08-25 20:51:51

+0

是的。 xsl:apply-templates和xsl:for-每個都改變上下文節點。有關答案的更多詳細信息,請提供更多詳細信息。 – 2012-08-26 07:14:16

相關問題