lunrjs is a client side search system that is perfectly suited for Jekyll and other static site systems.

Setting it up in Jekyll without any plugins (so it works on Github Pages) isn’t that hard only needs a couple of extra files and some Javascript. You can see the commit used to add lunr to this site here.

First off I needed a JSON file with all the data I want to make searchable in, I created /content.json which is generated by this:

I had issues getting the content safe for JSON, mainly with gists adding html etc… it got messy and I ended up truncating the number of words to 50 hoping that I wouldn’t have any special content in my posts in the first 50 words.

With lunr added to the template I added loadSearch() to the documents ready event to load search after the page has loaded.

A fair bit of that is unique to this site but the principle is the same for any site. On page load a new index is created and populate when the request for /content.json completes. Binding a couple of events to make the UI work how I wanted and to handle a user making a search.

The search is pretty simple the lunr index has a search method which you pass the search string to. It returns an array of results which I loop though and append to a list.

The order is set by the relevance of the result with the closer matches at the top.

This is a great feature which should help users find content easier.

Setting up lunr.js in Jekyll

Leave a Reply

Your email address will not be published. Required fields are marked *