I’ve had a project going on for a month or so to re-do a Confluence wiki into Markdown files, hence why I pusblished The Markdown Cheatsheet, and Jekyll categories based menu.
One thing that can be handy in a wiki is “back links” i.e. what other pages link to this page.
The Requirements
I want to automatically find, and display, all other pages in a Jekyll site that link to the existing page.
Ruby Plugin
Ok, so let’s just skip straight to the meaty bit 😂
In your Jekyll root directory, if you don’t already have a folder called _plugins
then create one.
Let’s create a file called _plugins/backlinks_generator.rb
Here’s a brief run down of what the Ruby script does:
- Creates 3 arrays: all_notes (i.e. a collection), all_post, all_pages.
- Concatinates the 3 arrays into one larger array called all_docs.
- In the current page that Jekyll is processing, loop through the all_docs array and find out if there is a link to the current page.
- Store the found results in the page/post.data as an array called backlinks ( i.e. page.backlinks or post.backlinks)
Some CSS
Yeah, just so things look nice 😝
The Jekyll layout
I learned quickly that everything seems to link to the home page (i.e. “/”).
So while writing a section in my layout I had to include an exclusion (i.e. {% if page.url != home.url %} )
Now each page has an array of backlinks, or doesn’t.
I’ll check if backlinks exists, by checking if it is greater than 0 (zero), and if it is, I can just loop through it !
Note:
You can disable showing the backlink on a per page / per post basis by using the front matter
—
showbacklinks: no
—
The Result
sweet screenshot goodness ….
1 Comment