Add Search To A Hugo Site
As with many sites these days, once they get beyond a certain size then search becomes an essential part of them. It can however we one of the trickier parts of a statically built websites because without a back-end to do the search for you then it has to be done client-side in the web browser.
HTML - Search Form
We need a html form to search with. This can either be on a search page of it’s own, any type of page or all pages as it works by submitting the form to the
/search endpoint. We need the id on the input to put the search query back in it when it loads.
Page - content/search/_index.md
Create a page for us to use as our search form and search results page. We set the layout to search and then create this layout to give us the ability to easily edit the html.
Layout - layout/_default/search.html
Our search page here contains a
<div> element for us to add our results into, as well as a
<div> element to store our loading message. In the layout we also define a template which we later use to populate a single search result entry. Finally, we load our JS libraries (from a cdn in this example, but feel free to self-host).
The Data - layouts/_default/index.json
All the work we’ve done up until now has been front-end workings, but we also build a index.json file as our data source (which is fetched from the JS).
Enable our index json file inside the
config.toml file (in the root of your project).
Although there are quite a few steps to the setup, if you follow the changes above you should end up with a working search form (like we do on this site!) Any issues let us know in the comments.
Site illustrations (of Hugo the rabbit) drawn by Carina Roberts.