Tapadocs: adding Pagefind for static site search capability

By John Keyes

May 20, 2024 at 10:54

cloudflare-pages

Pagefind

Pagefind is a fully static search library that aims to perform well on large site.”

Given we hope to add more posts to Tapadocs adding a search function will prove useful.

How will this integrate with Cloudflare Pages?

Tapadocs is hosted by Cloudflare Pages. Pagefind is a tool that creates the search index after the static site has been generated. In Tapadocs case, Hugo is the static site generator.

Cloudflare Pages has some presets but to run a custom build a specific one does not need to be selected. Instead, a custom npm script is used to first run hugo and then to run pagefind prior to deployment.

{
  "scripts": {
    "build": "hugo && pagefind --site public"
  },
  ...
}

Let’s see it in action

Searching for defer returns three results:

This isn’t exactly what we’d like, as the home page and the category page are listed in the results rather than the defer post itself.

Controlling what content is indexed

Pagefind has the ability to limit what pages get added to the index. If the data-pagefind-body attribute appears, then only pages with that attribute will be included in the index.

We add this to the main content section of the single.html template:

<div class="content" data-pagefind-body>
    {{ .Content }}
</div>

and now the search results are much improved:

Including the page category in the index

However, if we search for a word that is only in a page category, or an author’s name, it doesn’t appear in the results.

Again, data-pagefind-body to the rescue. This attribute can be used multiple times in a document:

<div class="list-item-meta" data-pagefind-body>
  <p>By {{ if .Params.email }}<a href="mailto:{{ .Params.email }}">{{ end }}{{ .Params.author }}{{ if .Params.email }}</a>{{ end }}</p>
  ...

and now categories:

and authors are indexed:

See Configuring the index for more details on way to configure the index.

Last updated: May 20, 2024 at 10:54