Skip to content

Instantly share code, notes, and snippets.

@danblakemore
Last active April 30, 2017 14:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danblakemore/1d11b18f475c6502d96b6474c813396b to your computer and use it in GitHub Desktop.
Save danblakemore/1d11b18f475c6502d96b6474c813396b to your computer and use it in GitHub Desktop.
Nested Jekyll page navigation without plugins
{% capture html %}
{% assign childCount = '' %}
{% comment %} Make sure there will be pages before making the ul tag. {% endcomment %}
{% 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 %}
{% capture childCount %}{{ childCount }}*{% endcapture %}
{% endif %}
{% endfor %}
{% if childCount.size > 0 %}
<ul>
{% if include.context == "/" %}
<li class="{% if page.url == "/" %}active{% endif %}">
<a href="{{ site.baseurl }}/">{{ site.title }}</a>
</li>
{% 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 %}">
{% capture subMenu %}{% include navigation.html context=entry.url %}{% endcapture %}
{% if subMenu.size > 0 %}
<a href="{{ site.baseurl }}{{ entry.url }}">{{ entry.title }}</a>
{% endif %}
{% unless subMenu.size > 0 %}
{% comment %}
This if/unless is optional. Useful if you want clicking on the non-text part
of the <li> row to expand, but you want have the leaf nodes of the navigation
tree browse when anywhere in the <li> is clicked, not just the text of the <a>.
If not, just remove the unless entirely and remove the if/endif around the <a>
above.
{% endcomment %}
<a class="make-the-internal-a-tag-inline-block-and-100%w/h" href="{{ site.baseurl }}{{ entry.url }}">{{ entry.title }}</a>
{% endunless %}
{{ subMenu }}
</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
{% endcapture %}{{ html | strip_newlines | replace:' ','' | replace:' ','' | replace:' ',' ' }}
@JacobDB
Copy link

JacobDB commented Apr 29, 2017

This is great! Is there a way I can check the depth of the menu, and conditionally add classes based on that?

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