问题
I am having trouble finding a good solution. The problem is I want a dynamically updated active class on my nav items, however I don't know how to do so. Can anyone help me with a solution for giving the nav item corresponding to the current page a certain class, automatically?
This is my layout.pug page:
doctype html html(lang="en") head include components/head body(id="page-top" role="document") include components/header main block main include components/footer
This is what I currently have for my header.pug file:
nav img.hamburger-menu(src="img/menu/menu-hamburger.svg" alt="Navigation Menu") ul(class="reveal") li a(href="index.html" ) Home li a(href="about.html") About li a(href="services.html") Services li a(href="contact.html") Contact
Then I have my index.pug and other rendered pages, which start like this:
extends ../layout block main section h1 Personally Professional
回答1:
There are a number of ways of going about this. One way is to pass a variable to each page, telling it which page it is.
Let's call this variable name
and pass it each page at render-time. You probably have a server (maybe in Node?) rendering these pages, each one for a different route. Well, instead of just instructing it to just render each of those pages, you also pass along a variable giving each route its name (e.g. {name: "index"}
). If it is not yet entirely clear to you how you can pass along a variable, have a look at the examples given in the Pug docs.
Now, each page knows its name/type, meaning that we can use this in the li
s: at each li
, we'll have a look whether it is the one (or, in other words, whether our wanted page name matches that of the list item).
To see whether it is active, we can conditionally add a class to that item. Here an example of how to do it for the index page (this code would augment what's already there in header.pug
):
li(class=(name === "index" ? "active" : undefined))
a(href="index.html") Home
...
(I'm assuming here that you already have an active
class in your CSS.)
回答2:
Here's another way. In layout.pug
, I would add the following block:
block nav
- var active = "index.html"
We use a block here so that pages that extend layout.pug
can override the cur
variable (and we default to index.html
as the active nav link).
Then, in header.pug
, you would use the cur
variable when setting the classes for each link (see gandreadis's answer for adding the active
class to your li
s).
Finally, on each of your pages, add the following (we'll use about.pug
as an example):
extends ../layout
block nav
- var cur = "about.html"
//- actual content
来源:https://stackoverflow.com/questions/45699338/add-active-nav-link-class-in-pug