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>

我想在同一个文件中多次使用这段代码。我可以将它放在模板中并在需要时调用它吗?

4

1 回答 1

3

是的 - 它叫做 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:call-template。例如 ...

<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 规范:命名模板
  2. XSLT 1.0 规范:命名模板
于 2012-08-14T00:30:44.053 回答