我正在尝试使用 XSLT 模板基本上重新创建 ASP.NET 母版页的功能。
我有一个“母版页”模板,其中包含存储在 .xslt 文件中的大部分页面 html。我有另一个特定于单个页面的 .xslt 文件,它采用表示页面数据的 xml。我想从我的新模板调用母版页模板,并且仍然能够插入我自己的将要应用的 xml。如果我可以传递一个参数,该参数允许我使用该参数作为名称调用模板,那就可以解决问题,但这似乎是不允许的。
基本上我有这个:
<xsl:template name="MainMasterPage">
<xsl:with-param name="Content1"/>
<html>
<!-- bunch of stuff here -->
<xsl:value-of select="$Content1"/>
</html>
</xsl:template>
还有这个:
<xsl:template match="/">
<xsl:call-template name="MainMasterPage">
<xsl:with-param name="Content1">
<h1>Title</h1>
<p>More Content</p>
<xsl:call-template name="SomeOtherTemplate"/>
</xsl:with-param>
</xsl-call-template>
</xsl:template>
发生的情况是,嵌套的 xml 基本上被剥离,插入的只是“TitleMore Content”
最佳答案
所提供代码的问题在这里:
<xsl:value-of select="$Content1"/>
这将输出 $Content1
顶部节点的所有文本节点后代的串联。 (如果它包含文档)或其第一个元素或文本子元素的字符串值(如果它是 XML 片段)。
您需要使用
<xsl:copy-of select='$pContent1'>
而不是
<xsl:value-of select='$pContent1'>
。
这会正确复制 $pContent1
的所有子节点
下面是修正后的转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:call-template name="MainMasterPage">
<xsl:with-param name="pContent1">
<h1>Title</h1>
<p>More Content</p>
<xsl:call-template name="SomeOtherTemplate"/>
</xsl:with-param>
</xsl:call-template>
</xsl:template>
<xsl:template name="MainMasterPage">
<xsl:param name="pContent1"/>
<html>
<!-- bunch of stuff here -->
<xsl:copy-of select="$pContent1"/>
</html>
</xsl:template>
<xsl:template name="SomeOtherTemplate">
<h2>Hello, World!</h2>
</xsl:template>
</xsl:stylesheet>
当此转换应用于任何 XML 文档(未使用)时,就会生成所需的正确结果:
<html>
<h1>Title</h1>
<p>More Content</p>
<h2>Hello, World!</h2>
</html>
关于xslt - 我可以将 xslt 模板的结果作为参数传递给另一个模板吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3269583/