Tuesday | 21 MAY 2024
[ previous ]
[ next ]

Adding Pagefind to my Blog

Title:
Date: 2023-07-02
Tags:  blog

My previous search was using sqlite from the browser and it worked relatively well but it was cumbersome. The search was also not that good. I could have spent some time fixing it up and made it a real project but I didn't have the patience for that.

Thanks to a post on lobste.rs, I learned about pagefind, a rust tool to generate a search index for a static site and it works quite well. The person builds a search index and also provides some javascript that you can load onto any page and give users a decent search experience. The very little I've used of it is pretty good.

You can install pagefind using cargo or you can download a precompiled binary. The command to generate your search is quite simple and the code you add to a page to add the search is very short. I'm curious what the core of the project is as it seems very similar to what I was doing with sqlite.

Installing pagefind:

cargo install pagefind

Running pagefind:

pagefind --source devlog

This will put a _pagefind directory in my devlog folder which is where my generated html live.

Then I can access the search by adding the following html:

    <link href="_pagefind/pagefind-ui.css" rel="stylesheet">
    <script src="_pagefind/pagefind-ui.js" type="text/javascript"></script>
    <script>
        window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({ element: "#search" });
        });
    </script>

This is what the search bar looks like:

And this is with a search:

With that we are done! I can now add a quick command to my blog generation that will also build a search index. This is what I used to do with sqlite as well but this feels much better and cleaner. This also incentivizes adding images to my blog posts as the search results will look quite a bit nicer with an image.