Using _data to Build Jekyll Navigation

I wanted an easy way to create my navigation menus and I found a great post here on using the new-ish ‘data’ feature of Jekyll.

What this allows us to do is centralize our navigation setup (pages and subpages) so any changes are kept out of our actual layout code.

Here’s what I did:

  • Add a new file called nav.yml in your _data directory
    • Create the _data directory if it doesn’t already exist
  • Paste this template into _data/nav.yml and edit it to fit your needs
- title: "Home"
  href: "/"

- title: "Blog"
  href: "/blog/"

- title: "Misc"
    - subtitle: "Example"
      subhref: "#"
    - subtitle: "Example2"
      subhref: "#"
  • Edit your _includes/naviation.html to match the following

<nav class="animenu">	
  <input type="checkbox" id="button">
  <label for="button" onclick>Menu</label> 
    {% for nav in %}
      {% if nav.subcategories != null %}
	  <a href="{{ site.url }}{{ nav.url }}">{{ nav.title }} &#x25BC;</a>
	    {% for subcategory in nav.subcategories %}
	      <li><a href="{{ site.url }}{{ subcategory.subhref }}">{{ subcategory.subtitle }}</a></li>
	    {% endfor %}
	{% elsif nav.title == page.title %}
	  <li class="active"><a href="{{ nav.url }}">{{ nav.title }}</a></li>
	{% else %} 
	  <a href="{{ site.url }}{{ nav.href }}">{{ nav.title }}</a></li>
      {% endif %}
    {% endfor %}

Now any time you want to update your navigation just edit the _data/nav.yml file and rebuild your site.