有没有办法内联调用XSLT模板

时间:2009-11-24 20:27:53

标签: design-patterns xslt anonymous-function processing-instruction

如何内联调用XSLT模板?例如,而不是:

<xsl:call-template name="myTemplate" >
<xsl:with-param name="param1" select="'val'" />
</xsl:call-template>

我可以使用XSLT内置的函数调用样式,如下所示:

<xls:value-of select="myTeplate(param1)" />

3 个答案:

答案 0 :(得分:4)

在XSLT 2.0中,您可以使用xsl:function

定义自己的自定义函数

XML.com上的一篇文章,描述了如何在XSLT 2.0中编写自己的函数:http://www.xml.com/pub/a/2003/09/03/trxml.html

<xsl:stylesheet version="2.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:foo="http://whatever">

  <!-- Compare two strings ignoring case, returning same
       values as compare(). -->
  <xsl:function name="foo:compareCI">
    <xsl:param name="string1"/>
    <xsl:param name="string2"/>
    <xsl:value-of select="compare(upper-case($string1),upper-case($string2))"/>
  </xsl:function>

  <xsl:template match="/">
compareCI red,blue: <xsl:value-of select="foo:compareCI('red','blue')"/>
compareCI red,red: <xsl:value-of select="foo:compareCI('red','red')"/>
compareCI red,Red: <xsl:value-of select="foo:compareCI('red','Red')"/>
compareCI red,Yellow: <xsl:value-of select="foo:compareCI('red','Yellow')"/>
  </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:1)

在第一个示例中,XSLT的语法是正确的。你也可以写

<xsl:call-template name="myTemplate" >
<xsl:with-param name="param1">val</xsl:with-param>
</xsl:call-template>

我不确定你在第二个代码片段中想要做什么('val'缺失并且有两个拼写错误(xls和myTeplate))但是它无效XSLT.I n

更新如果我现在理解您的问题,那么“是否有替代XSLT模板的语法?”但“我可以在XSLT中编写自己的函数吗?”。

是的,你可以。这是一个有用的介绍。请注意,您必须在库中提供Java代码,这可能不容易分发(例如在浏览器中)。试试http://www.xml.com/pub/a/2003/09/03/trxml.html

答案 2 :(得分:1)

使用processing-instruction和应用参数的匹配模板执行此操作:

<?xml version="1.0" encoding="utf-8"?>
<!-- Self-referencing Stylesheet href -->
<?xml-stylesheet type="text/xsl" href="dyn_template_param.xml"?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"
            >

<!--HTML5 doctype generator-->
<xsl:output method="xml" encoding="utf-8" version="" indent="yes" standalone="no" media-type="text/html" omit-xml-declaration="no" doctype-system="about:legacy-compat" />

<!--Macro references-->
<?foo param="hi"?>
<?foo param="bye"?>

<!--Self-referencing template call-->
<xsl:template match="xsl:stylesheet">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="/">
  <!--HTML content-->
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    </head>
    <body>
      <!--Macro template calls-->
      <xsl:apply-templates/>
    </body>
  </html>
</xsl:template>

<xsl:template match="processing-instruction('foo')">
  <xsl:param name="arg" select="substring-after(.,'=')"/>
  <xsl:if test="$arg = 'hi'">
    <p>Welcome</p>
  </xsl:if>
  <xsl:if test="$arg = 'bye'">
    <p>Thank You</p>
  </xsl:if>
</xsl:template>
</xsl:stylesheet>

<强>参考

相关问题