L
L
litash2018-06-27 20:50:34
JavaScript
litash, 2018-06-27 20:50:34

How to show content on url change in pug, jade?

Hello, when you change the url, you need to show a specific block.
I'm trying to do this:
if window.location.href === "/about"
div
| about
else if window.location.href === "/home"
div
| home
Galp throws an error Cannot read property 'location' of undefined. Please tell me the correct way.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Proskurin, 2018-06-27
@litash

pug works statically, i.e. after it is compiled, an html file is created, and this html file is already opened in the browser. If you write like this

if a > 10
div hello
else
div ne hello

then if at the time of compilation a was more than 10, then a line will get into the html file and nothing else, until the next compilation (and if a is already less there, then ne hello will get there). Therefore, pug knows nothing about the window object and the address of the current page. You can set the address in the page header by specifying your variable, for example currentPage. And everywhere on different pages indicate it differently

J
Jumandjilos, 2018-06-27
@Jumandjilos

When rendering a template, you can add a variable, for example:

if x
div
| about
else if y
div
| home

Routes:
router.get('/about', (req, res) => {
res.render('ИмяШаблона', {x})
}

With /home it is similar, but instead of x, put y.

P
profesor08, 2018-06-27
@profesor08

I suppose you want to put some emphasis on the menu item if you click on it. You need mixins.

mixin menu(activeItem)
  .menu
        a.menu-item(href="#" class={"is-active": activeItem === "page-1"})
        a.menu-item(href="#" class={"is-active": activeItem === "page-2"})
        a.menu-item(href="#" class={"is-active": activeItem === "page-3"})
        a.menu-item(href="#" class={"is-active": activeItem === "page-4"})

Next, on page-1, insert the code instead of the menu, so when you view page-1, the item will be highlighted. Similarly for page-2, page-3 and so on.
+menu("page-1")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question