static-sitemetalsmith

How natively to set active menu item with metalsmith?


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?


Solution

  • 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
    ---