on
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, be one of the trickier parts of a statically built website because without a back-end to do the search for you, it has to be done client-side in the web browser using JavaScript.
Luckily, solutions to this problem already exist and we show off one these solutions below which uses both FuseJS and MarkJS. This code is based on a gist by eddiewebb - but is built with “vanilla” JavaScript instead of jQuery.
HTML - Search Form
We need a html form to search with. This can either be on a search page of it’s own, any group of pages or all pages - as it works by submitting the form to the /search
endpoint. We need the id attribute on the input to put the search query back into it when it loads.
|
|
Page - content/search/_index.md
Create a page for us to use as our search form and search results page. In the markdown, we specify the layout to ‘search’ and then we create this layout (in the next step) 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 (#search-results), as well as a <div>
element to store our loading message (.search-loading). In the layout we also define a template which we will later use in the JS 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).
|
|
JS
The main chunk of the code comes as JavaScript for this as we need to bring it altogether. We read the url parameters to get the query then pass that to FuseJS and MarkJS the write the results back to our page.
|
|
The Data - layouts/_default/index.json
All the work we’ve done up until now has been front-end workings, but we also need to build a index.json file which will act as our data source (which is fetched from the JS).
|
|
Config
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.