Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Nested Jekyll page navigation without plugins
{% capture html %}
{% if include.context == "/" %}
<li class="{% if page.url == "/" %}active{% endif %}">
<a href="{{ site.baseurl }}/">{{ site.title }}</a>
{% endif %}
{% assign entries = site.pages | sort: "path" %}
{% for entry in entries %}
{% capture slug %}{{ entry.url | split: "/" | last }}{% endcapture %}
{% capture current %}{{ entry.url | remove: slug | remove: "//" | append: "/" }}{% endcapture %}
{% if current == include.context %}
<li class="{% if page.url contains entry.url %}active{% endif %}">
<a href="{{ site.baseurl }}{{ entry.url }}">{{ entry.title }}</a>
{% include navigation.html context=entry.url %}
{% endif %}
{% endfor %}
{% endcapture %}{{ html | strip_newlines | replace:' ','' | replace:' ','' | replace:' ',' ' }}

kasperisager commented Mar 8, 2014

A simple nested page navigation list for Jekyll that highlights the currently active tree.


{% include navigation.html context="[top-level-path]" %}

If you wanted to list all pages starting with the root, you'd do:

{% include navigation.html context="/" %}

If you instead wanted to list everything beneath /foo/bar, you'd do:

{% include navigation.html context="/foo/bar/" %}

Thank you so much for this! It wasn't working for me earlier but I once I updated Jekyll it worked beautifully!

This is really slick, thanks for this!

aliok commented Mar 21, 2016

Great, works perfect!

Great stuff, thanks!

8wgremlin commented Jun 20, 2016 edited

This is awesome, Thanks!

I'm trying to convert this over to a bootstrap navigation structure and need to place a class on the 'li' element if it has any children
as well adding some code like this:

<ul class="nav navbar-nav"> <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul>

any suggestions?

Check out the fork I just made. It has some useful additions if you want to add expandable/collapsable features to the menu (specifically not having every leaf include an empty <ul> below it).

I think a cleaner approach is to use Jekyll's group_by filter in combination with the Page#dir method, see my example gist.

YouDuk commented Jul 5, 2017

HI, thanks for your posting. but I can't know how to insert this file. where should I add this file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment