【问题标题】:Change CSS class depending on URL in XSLT根据 XSLT 中的 URL 更改 CSS 类
【发布时间】:2014-09-07 08:32:05
【问题描述】:

我正在尝试制作一个可以在使用 XSLT 的网站上的所有页面上使用的菜单。

我有一个 XSL:

<xsl:template match="header/menu">
  <div class="header__menu">
    <xsl:apply-templates select="item"/> 
  </div>
</xsl:template>

<xsl:template match="menu/item">
  <div class="header__menu-item">
    <a class="link">
        <xsl:attribute name="href">
            <xsl:value-of select="../item/@url"/>
        </xsl:attribute>
        <xsl:value-of select="."/>
     </a>
  </div>
</xsl:template>

XML:

 <header>
    <menu>
      <item url="#">Work</item>
      <item url="#">About</item>
      <item url="#">Blog</item>
    </menu>
 </header>

我想根据页面更改菜单项的 CSS 类(页面打开且没有链接时的活动类)。

我曾想过尝试 xsl:choose 构造并检查页面 URL,但不知道该怎么做。

有什么建议吗?提前致谢。

【问题讨论】:

  • XSLT 本身不会知道页面 URL,所以您必须将当前 URL 作为参数传递?您目前如何调用 XSLT 来执行转换? (例如,在 PHP、ASP.Net、JavaScript 等中?)。
  • 我目前使用 php。我在目录中有一个 index.php 文件,它调用一个 xsl(导入 header.xsl 和其他)和一个页面的 xml。

标签: xml xslt menu


【解决方案1】:

虽然您可以在 XSLT 中使用扩展方法来获取 URL,但通过 PHP 将 URL 作为参数传递给 XSLT 可能更容易。请参阅此文档,例如:http://docs.php.net/manual/en/xsltprocessor.setparameter.php

在您的 XSLT 本身中,您将有一个像这样定义的参数

<xsl:param name="url" />

就使用而言,您可以使用 xsl:choose,因此您的 XSLT 可能看起来像这样(在这种情况下,我将 css 类放在 a 标签,但如果你愿意,它可以很容易地放在包含 div 的标签上。

<xsl:template match="menu/item">
  <div class="header__menu-item">
    <a class="link" href="{@url}">
     <xsl:attribute name="class">
        <xsl:choose>
           <xsl:when test="$url = @url">active</xsl:when>
           <xsl:otherwise>inactive</xsl:when>
        <xsl:choose>
      </xsl:attribute>
      <xsl:value-of select="."/>
    </a>
  </div>
</xsl:template>

顺便说一句,请注意在创建现有 href 属性时使用“属性值模板”。花括号{ } 表示要计算的表达式,而不是字面输出。

【讨论】:

  • 感谢 Tim C。我还没有完全弄清楚如何将 url 传递给 xsl 参数。
  • 如果有人需要的话,可以得到关于在 PHP 中传递 URL 的答案:stackoverflow.com/questions/25826220/…
猜你喜欢
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多