Add Search To A Hugo Site
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).
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).
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.