是)我有的?
我有一个ASP.NET项目,其中有一个XSLT文件,定义了许多模板.根据用户选择,一次只能使用一个模板,以在网页上显示内容.它看起来像这样:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="TemplateName"></xsl:param>
<xsl:template match="Title_Only">
...template Title_Only body...
</xsl:template>
<xsl:template match="Image_Only">
...template Image_Only body...
</xsl:template>
<xsl:template match="Title_And_Image">
...template Title_And_Image body...
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
我想要的是?
我想将模板名称TemplateName作为参数传递,并能够在数据上应用相应的模板.
有人可以告诉我如何实现这一目标?
您不能在XSLT 1.0中的匹配模式中使用param或变量的值.但是,您可以从单个模板有条件地应用模板,如下所示:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="TemplateName"/>
<xsl:template match="/">
<xsl:apply templates select="something[some_condition=$TemplateName]"/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
...然后只需设置模板以分别匹配每种类型的节点.模板将仅应用于与您的select表达式匹配的内容,这些内容基于参数.
有条件地应用模板的示例
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="TemplateName" select="'Title_Only'" />
<xsl:template match="/">
<xsl:apply-templates select="test/val[@name=$TemplateName]" />
</xsl:template>
<xsl:template match="val">
<xsl:value-of select="@name" />
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
适用于此输入:
<test>
<val name="Title_Only" />
<val name="Image_Only" />
<val name="Title_And_Image" />
</test>
Run Code Online (Sandbox Code Playgroud)
生产:
Title_Only
Run Code Online (Sandbox Code Playgroud)
......基于的价值$TemplateName.(注意,此示例使用变量,但想法是相同的.)
使用模式分离模板
如果在每种情况下确实需要完全不同的模板,请使用模式.这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="TemplateName" select="'Title_Only'" />
<xsl:template match="/">
<xsl:choose>
<xsl:when test="$TemplateName='Title_Only'">
<xsl:apply-templates select="test/val" mode="Title_Only" />
</xsl:when>
<xsl:when test="$TemplateName='Image_Only'">
<xsl:apply-templates select="test/val" mode="Image_Only" />
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="test/val" mode="Title_And_Image" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="val" mode="Title_Only">
<xsl:value-of select="@title" />
</xsl:template>
<xsl:template match="val" mode="Image_Only">
<xsl:value-of select="@img" />
</xsl:template>
<xsl:template match="val" mode="Title_And_Image">
<xsl:value-of select="@title" />/
<xsl:value-of select="@img" />
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
适用于此来源:
<test>
<val title="some title" img="some image"/>
</test>
Run Code Online (Sandbox Code Playgroud)
生产:
some title
Run Code Online (Sandbox Code Playgroud)
基于参数的值使用期望的模板.
| 归档时间: |
|
| 查看次数: |
2666 次 |
| 最近记录: |