代码之家  ›  专栏  ›  技术社区  ›  chepseskaf Nick Holt

XSLT:如何在不复制代码的情况下创建条件链接

  •  2
  • chepseskaf Nick Holt  · 技术社区  · 15 年前

    生成的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>
    

    我想知道如何简化我的代码,如何停用节点 <a></a> ?

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

    <a> href ?

    2 回复  |  直到 15 年前
        1
  •  2
  •   kennytm    15 年前

    你可以把动作文本作为变量。这个变量仍然出现在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 tag,你可以用

      <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 ,所以不要依赖它。)

        2
  •  0
  •   codymanix    15 年前