Dead simple breadcrumbs for GitHub Pages
In a previous article, I presented a simple technique to generate breadcrumbs on a Jekyll website; and, since it didn’t require any plugin, it can be used on GitHub Pages too. This technique used the URL of the page to generate the breadcrumbs; today, I’m presenting an even simpler solution base on the page’s categories.
Photo by Artur Rutkowski on Unsplash
Using the page’s category instead of using the page’s URL presents a huge benefit: it decouples the breadcrumbs from the URL. Now, you can change the navigation on the site without changing any URLs, so without breaking any links.
Depending on the configuration, Jekyll can also use the page category to determine its URL. In that case, the breadcrumbs are aligned with the URL of the page, so we get the same result as before, but with increased flexibility.
Listing the possible paths
As before, we use a data file to store the breadcrumb information. In this case, we just want to associate the name of a category with a breadcrumb name and URL. Here is our _data/breadcrumbs.yaml
:
doc:
title: Documentation
url: /doc/
api:
title: API
url: /api/
faq:
title: FAQ
url: /faq/
news:
title: News
url: /news/
For example, the category doc
corresponds to the page Documentation
located at /doc/
.
Display the crumb
Now, let’s see how we can generate the HTML code. We just need to find the breadcrumb for each category of the page.
Here is the complete code in:
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{{ site.baseurl }}">Home</a>
</li>
{%- for category in page.categories -%}
{%- assign crumb = site.data.breadcrumbs[category] -%}
{%- if crumb -%}
<li class="breadcrumb-item">
<a href="{{ crumb.url | prepend: site.baseurl }}">
{{ crumb.title }}
</a>
</li>
{%- endif -%}
{%- endfor -%}
<li class="breadcrumb-item active">
<a href="{{ page.url | prepend: site.baseurl }}">
{{ page.title }}
</a>
</li>
</ol>
An example
As an example, let’s see how the code works for the page JsonArray.
Here is the front matter:
title: JsonArray
categories: doc api
The beginning of the template produces the breadbrumb for the Home
:
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/">Home</a>
</li>
Then, the for
loop extracts the first category: doc
. The assign
statement retreives the matching breadcrumb from site.data.breadcrumbs
. This breadcrumb is named Documentation
and points to /doc/
. So, the first iteration of the loop produces:
<li class="breadcrumb-item">
<a href="/doc/">
Documentation
</a>
</li>
The same happends for the second category: api
. The second iteration produces:
<li class="breadcrumb-item">
<a href="/api/">
API
</a>
</li>
Finally, the end of the template produces the breadcrumb for the current page:
<li class="breadcrumb-item active">
<a href="/api/jsonarray/">
JsonArray
</a>
</li>
</ol>
Here a screen capture of the result: