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"
  subcategories:
    - subtitle: "Example"
      subhref: "#"
    - subtitle: "Example2"
      subhref: "#"

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

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