How to create a dynamic menu in Jekyll that auto-populates nav items when creating new pages


I am wondering how to go about creating a dynamic menu in Jekyll that automatically populates the navigation with nav items whenever a new page is created to make it easier for clients to maintain. I read an article - that touched a bit on the subject, but it was geared toward just sub-nav items. Has anyone had any experience in doing something like this?



You can loop through site.pages or site.posts to populate your nav logic. I believe Jekyll’s default theme Minima does this to list all of the site’s pages in the header.


It is a bad idea to do this automatically. However, it is very easy to achieve. Here is the code:

  {% for item in site.pages %}
    <li {% if page.url contains item.url %}class="active"{% endif %}><a href="{{ item.url }}">{{ item.title }}</a></li>
  {% endfor %}


To define the order of appearence, you might want to add a front matter variable called ‘order’ to the pages and add a different pagenumber to this variable on each page. The code should sort the pages before looping over them. That looks like this:

{% assign sitepages = site.pages | sort: order %}
{% for item in site.pages %}
{% endfor %}

Happy coding!


Thanks a bunch for help and link. Also, why would it be a bad idea, just curious?

Thanks again!


It is a bad idea since this script does not allow you to make unlisted pages. Adding pages to your menu is not a regular thing you want to do, I guess, while creating pages (hopefully) is.