将类添加到当前导航项

时间:2016-03-02 09:09:38

标签: javascript pug harp

我有一个关于在当前菜单项中添加类的简单问题。

我有以下页面结构:

- index.jade
- about.jade
- articles/
  - _data.json
  - index.jade
  - blog-post-1.jade
  - blog-post-2.jade
- contact.jade

现在我创建了一个名为.active的类,它只适用于根页面(索引关于联系人 )但是当我点击 /articles 时,活动课程没有被添加到菜单中的文章 li

我正在使用Harp网站上的代码片段:

ul
  li(class="#{ current.source == 'index' ? 'active' : '' }")
    a(href="/") Home
  li(class="#{ current.source == 'about' ? 'active' : '' }")
    a(href="/about") About
  li(class="#{ current.source == 'articles' ? 'active' : '' }")
    a(href="/articles") Articles
  li(class="#{ current.source == 'contact' ? 'active' : '' }")
    a(href="/contact") Contact

无论我尝试什么,我似乎无法让.active菜单类在 /articles 上工作,也不会在任何文章页面上工作: articles/blog-post-1 articles/blog-post-2 等等。

同样在Harp网站上,我看到你可以添加:

{
  path: ["articles", "hello-world"],
  source: "hello-world"
}

但我不知道在哪里添加它。我已将其添加到articles/_data.json文件中,但无效。

1 个答案:

答案 0 :(得分:3)

因此,您实际上不必添加当前源和当前路径,这是Harp在模板中提供的功能之一。您可以随时在页面上显示它:

pre: code= JSON.stringify(current, 0, 2)

假设您在第一篇博客帖子页面上,您会得到类似的内容:

{
  source: "blog-post-1"
  path: [
    "articles",
    "blog-post-1"
  ]
}

因此,在这种情况下,您的导航未被激活,因为current.source实际上不是articles,而是blog-post-1blog-post-2。解决问题的最快方法是:

li(class="#{ current.path[0] === 'articles' ? 'active' : '' }")
  a(href="/articles") Articles

这也应该适用于文章索引页面,其中Harp的current object将如下所示:

{
  source: "index"
  path: [
    "articles",
    "index"
  ]
}