我熟悉使用模板,键关闭属性如下(例如键关闭foo
的存在):
<xsl:template match="something[@foo]">
<xsl:template match="something[not(@foo)]">
然而,如果这些模板的大部分内容是相同的,是否有更好的方法仍然使用模板,因为社区似乎更喜欢它们?或者解就是用xsl:choose
。显然,最好不要编写必须在两个模板中维护的重复代码。
编辑:下面是我的模板集:
<xsl:template match="item[not(@format)]">
<td class="{current()/../@name}_col status_all_col">
<xsl:value-of select="current()"/>
<xsl:value-of select="@units"/>
</td>
</xsl:template>
<xsl:template match="item[@format]">
<td class="{current()/../@name}_col status_all_col">
<xsl:value-of select="format-number(current(), @format)"/>
<xsl:value-of select="@units"/>
</td>
</xsl:template>
下面是我现在使用choose:
<xsl:template match="item">
<td class="{current()/../@name}_col status_all_col">
<xsl:choose>
<xsl:when test="@format">
<xsl:value-of select="format-number(current(), @format)"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="current()"/>
</xsl:otherwise>
</xsl:choose>
<xsl:value-of select="@units"/>
</td>
</xsl:template>
在这种情况下我肯定会使用xsl:choose
。
只是为了演示如何使用模板而不需要重复代码:
<xsl:template match="item">
<td class="{../@name}_col status_all_col">
<xsl:apply-templates select="." mode="format"/>
<xsl:value-of select="@units"/>
</td>
</xsl:template>
<xsl:template match="item[not(@format)]" mode="format">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="item[@format]" mode="format">
<xsl:value-of select="format-number(., @format)"/>
</xsl:template>
但是我看不出这有什么好处。相反,它患有GOTO综合征。
顺便说一句,这可能不是最好的例子,因为我认为提供一个空字符串作为format-number()
函数的第二个参数将导致数字按原样返回。
所以你可以只用一个模板来匹配所有的:
<xsl:template match="item">
<td class="{../@name}_col status_all_col">
<xsl:value-of select="format-number(current(), @format)"/>
<xsl:value-of select="@units"/>
</td>
</xsl:template>