1

i got a simple static site with a main navigation. working with the metalsmith generator.

Is there a native way to set current menu items active?


My current unautomated solution:

I just made a workaround like following.

A MD file page1.md as source of content with some variables i can define at top:

---
title: this is the site title
currentPage1: current
layout: main.html
---

<article class="featurette">
    <p class="lead">Some content text...</p>
</article>

and my layout HTML file main.html. Where handlebars is used as engine. i just post the part of the menu here:

<ul class="nav">
        <li>
          <a href="/page1/" class="{{ currentPage1 }}">Link to Page1</a>
        </li>
        <li>
          <a href="/page2/" class="{{ currentPage2 }}">Link to Page2</a>
        </li>    
</ul>

both are going through the metalsmith rendering. I got a current class on the Page1 in the menu.


Question

My solution is working so far, but as my site scales. I need to define the "current" for every site again and again. If I don't watch out this will lead to misconfiguration... I do like to have freedom on my main navigation markup, as there are some specialities in. So I'm fine with creating this for new pages by myself.

Can i set active menu items somehow with the metalsmith-permalinks or metalsmith-canonical plugin or does there exists a metalsmith plugin suited for this case or maybe with another clever JS manipulation?

André Kelling
  • 1,575
  • 16
  • 23

1 Answers1

1

Use metalsmith-collections to create a collection of pages

.use(collections({
    pages: {
        pattern: '*.html'
    }
}))

Then in your template loop through them to create your links:

{{#each collections.pages}}
    <li>
         <a href="{{path}}" {{#if_eq ../id this.id}} class="active" {{/if_eq}}>{{title}}</a>
     </li>
 {{/each}}

You will need to register a block helper like this: Handlebars.js if block helper ==

Make sure each page ID is unique.

For example:

---
id: phillip
layout: base.hbs
tagline: I haven't thought of one.
pagename: phils page
href: /phil/
navorder: 3
private: true
---
James Khoury
  • 21,330
  • 4
  • 34
  • 65
  • hey, i need to try your solution the next days. `path` and `id` are variables provided with the `collections` plugin? i know for sure i don't have `path` available by default – André Kelling Dec 11 '18 at 09:22
  • @AndréKelling No I'd has to be specified in the page metadata and I think there might be a plugin to provide the path but I just put it on the page. – James Khoury Dec 11 '18 at 09:28
  • --- id: phillip layout: base.hbs tagline: I haven't thought of one. pagename: phils page href: /phil/ navorder: 3 private: true --- **edit: can't put new lines in. I will add this as an example** – James Khoury Dec 11 '18 at 09:29