hugo-client-side-search-template
hugo-client-side-search-template copied to clipboard
A lightweight, fuzzy, client-side search template for Hugo
Hugo client-side search template
A lightweight, fuzzy, client-side search template for Hugo.
Links
- Demo: https://hugo-client-side-search-template.netlify.app/
- Forum: https://discourse.gohugo.io/t/a-lightweight-fuzzy-client-side-search-template-for-hugo/39684
Dependencies
Just one, Fuse.js, which allows fuzzy matching, among other cool things.
How it Works
At a high-level:
- A JSON index is generated by hugo during the site build
- You navigate to the deployed site
- The DOMContentLoaded event fires
- The JSON index is fetched
- Fuse.js is instantiated with the JSON index
- You do a search which fires the keyup event
- Fuse.js is queried for hits
- Matched substrings are highlighted (with CSS that you craft)
- The DOM is updated with hits (with HTML that you craft)
Relevant Files
config.yaml
The outputs.home
config must be set to allow JSON.
layouts/index.json.json
Iterate all regular pages. For each page, build a dict of relevant keys, then append the dict to a slice. jsonify the slice.
layouts/partials/scripts.html
Get the JS resource, build it, then bundle it. Put this right before your closing </body>
tag.
layouts/partials/search.html
I chose to use the homepage as the search page, but you can use whatever page you want.
Just make sure the HTML elements in this partial are present.
assets/js/fuse.mjs
I chose to keep the minified Fuse.js library in the repo.
You could also do it via <script>
element, or npm
. See the Fuse.js installation docs.
assets/js/types.ts
Update the Page
interface with the relevant keys from your hugo site.
assets/js/main.ts
Look for occurrences of TEMPLATE_TODO
then follow the directions.
Credit
Sample EVA data provided by https://catalog.data.gov/dataset/extra-vehicular-activity-eva-us-and-russia.