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:

- title: "Home"
  href: "/"

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

- title: "Misc"
    - subtitle: "Example"
      subhref: "#"
    - subtitle: "Example2"
      subhref: "#"

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