【问题标题】:XSLT : How to create conditional link without duplicating codeXSLT:如何在不重复代码的情况下创建条件链接
【发布时间】:2010-07-21 14:58:13
【问题描述】:

生成的 HTML 页面包含有时在我的页面中不存在的参考链接。我应该将此链接显示为一个简单的标签。 目前已完成:

<xsl:choose>
 <xsl:when test="$nb_action != 0">
  <a href="#action">Action (offensive, defensive, reconnaissance)</a>
 </xsl:when>
 <xsl:otherwise>
  Action (offensive, defensive, reconnaissance)
 </xsl:otherwise>
</xsl:choose>

我想知道如何简化我的代码,如何停用节点&lt;a&gt;&lt;/a&gt;

我的第一个想法是委托一个特殊的 css 类:

<a href="#action">
 <xsl:if test="$nb_action = 0">
  <xsl:attribute name="class">inactive</xsl:attribute>
 </xsl:if>Action (offensive, defensive, reconnaissance)
</a>

但它仍然是一个链接......

以下解决方法:

<a><xsl:if test="$nb_action != 0">
  <xsl:attribute name="href">#action</xsl:attribute>
 </xsl:if>Action (offensive, defensive, reconnaissance)</a>

不带href的html标签写&lt;a&gt;是否正确?

【问题讨论】:

    标签: html xslt


    【解决方案1】:

    您可以将该操作文本作为变量。这个变量仍然出现在 3 个地方。

    <xsl:variable name="textval">
    Action (offensive, defensive, reconnaissance)</xsl:variable>
    <xsl:choose>
     <xsl:when test="0">
      <a href="#action"><xsl:copy-of select="$textval"/></a>
     </xsl:when>
     <xsl:otherwise>
      <xsl:copy-of select="$textval"/>
     </xsl:otherwise>
    </xsl:choose>
    

    编辑:或者,如果您不介意额外的、无用的span 标签,您可以使用

      <xsl:variable name="condition" select="---condition-here---"/>
    
      <xsl:variable name="tagname">
       <xsl:choose>
        <xsl:when test="$condition">a</xsl:when>
        <xsl:otherwise>span</xsl:otherwise>
       </xsl:choose>
      </xsl:variable>
    
      <xsl:element name="{$tagname}">
       <xsl:if test="$condition">
        <xsl:attribute name="href">#action</xsl:attribute>
       </xsl:if>
       Action (offensive, defensive, reconnaissance)
      </xsl:element>
    

    (在 Firefox 中,如果我们将 $tagname 设置为空字符串,则根本不会应用该元素。但处理器也可以raise an error,所以不要依赖它。)

    【讨论】:

    • 一个小问题:为了将 $textval 声明为字符串数据类型,请使用 select="'Action (offensive, defensive, reconnaissance)'"。否则它将被定义为一个结果树片段。
    • @Alejandro:实际上我相信树片段是 OP 想要的,我应该使用 copy-of 而不是 value-of。已更新。
    【解决方案2】:

    您不将字符串 Action(..) 存储到变量中并存储在代码中吗?

    【讨论】:

    • 我怀疑这个提议,但由于可以修改属性,我认为有可能修改项目...
    猜你喜欢
    • 1970-01-01
    • 2014-10-21
    • 2021-12-14
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多