2016-08-30 26 views
0

我熟悉使用模板,键关机属性如下(如钥匙关闭的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> 

这里是我当前使用中进行选择:

<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> 
+0

答案取决于两个模板的实际内容。 - P.S.使用'xsl:choose'没有任何问题。 –

+0

我添加了我的特定模板。 – Bryant

回答

0

我肯定会在这种情况下使用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 syndrome


顺便说一句,这可能不是最好的例子,因为我相信,供给一个空字符串作为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> 
+0

感谢您对可能不需要分支行为的评论。然而,事实证明,我得到了一些非数字的数据,格式数字只是为那些返回“NaN”。 – Bryant

+0

“*我有一些非数字的数据*”啊,这很有道理。 - 还要注意,在XSLT 2.0中,你可以使用'xsl:next-match'。 –