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?


1 Like

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!

1 Like

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. looks like a really good theme for github documentation.

Indeed as mentioned before minima uses approach to iterate over pages (I think alphabetically)

If you at the top you’ll see that it uses header_pages as a list set if config and then falls back to pages it can find on its own.

Also for interest see the jekyll menus plugin. I haven’t tried it but allows nesting of menus and setting of weights and it looks like either frontmatter or a data file.