Behind The Scenes: Edition 2 - Adding Search To A Static Site
We recently added the ability to search on our website. In total, we’re using: React and Lunrjs for our search functionality. Lunrjs is simpler, javascript version of solr which is an open source enterprise search platform. If you’ve heard of elasticsearch, solr is a similar product to that.
First, we build out jekyll documents into a JSON array and expose them to the window object using javascript:
const documents = [];
// we make the array of categories a string so our search index will pick up each
{ % for post in site.posts % }
const doc = {
excerpt: "",
title: "",
type: "",
categories: [],
categoriesString: "",
date: "",
link: ""
};
documents.push(doc);
{ % endfor % }
There is some complexity that we handle by passing in flags to which type of collection we want to index on that particular page:
- If we’re on the /blog page of our site we only want to search blog entries. Makes sense right? If we’re on the /social page to view our social media posts we only want to search social posts.
- If we’re on the home page we want to search blog and social posts so in that case we pass the flag as true for both the blogDocs and the socialDocs.
{ % if page.blogDocs % }
{ % for post in site.posts % }
// same loop heres previous
{ % endfor % }
{ % endif % }
{ % if page.socialDocs % }
{ % for post in site.social-posts % }
// same loop heres previous
{ % endfor % }
{ % endif % }
// in our respective templates
social.html:
socialDocs: true
blog.html
blogDocs: true
index.html (homepage):
socialDocs: true
blogDocs: true
Check part two of how we integrated this search with React to render the results.