本博客主题添加pagefind作为搜索引擎教程

本站hugo源码结构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{
  ".": [
    ".gitignore",
    ".gitmodules",
    "deploy.sh",
    "hugo.toml",
    "pagefind.yml"
  ],
  "archetypes": [
    "default.md"
  ],
  "assets": { // 魔改主题时添加
    ".": ["jsconfig.json"],
    "css": {
      ".": ["_variables.scss"],
      "_page": ["_archive.scss", "_index.scss"],
      "_partial": {
        ".": ["_header.scss"],
        "_archive": ["_terms.scss"],
        "_single": ["_code.scss"]
      }
    }
  },
  "content": { // 博客贴文
    "posts": {
      "CentOS安装zsh及其插件": ["index.md"],
      "Colly学习笔记": ["index.md"]
    }
  },
  "layouts": { // 魔改主题时添加
    ".": ["index.html"],
    "taxonomy": ["terms.html"],
    "_default": ["baseof.html"]
  },
  "static": [
    "search.html" // pagefind ui
  ],
  "themes": {
    "DoIt": "省略...."
  }
}

在博客根目录新建static目录,并在其中新建search.html,内容如下(完全照搬pagefind官方)

1
2
3
4
5
6
7
8
9
<link href="pagefind/pagefind-ui.css" rel="stylesheet">
<script src="pagefind/pagefind-ui.js"></script>

<div id="search"></div>
<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        new PagefindUI({ element: "#search", showSubResults: true });
    });
</script>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[menu]
  [[menu.main]]
    identifier = "posts"
    name = "文章"
    url = "/posts/"
    # 当你将鼠标悬停在此菜单链接上时, 将显示的标题
    title = ""
    weight = 1
  [[menu.main]]
    identifier = "tags"
    name = "标签"
    url = "/tags/"
    title = ""
    weight = 2
  [[menu.main]]
    identifier = "categories"
    name = "分类"
    url = "/categories/"
    title = ""
    weight = 3
  [[menu.main]]
    identifier = "pg"
    name = "pagefind"
    url = "/search.html"
    title = ""
    weight = 4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Pagefind 会自动在当前目录下查找pagefind.yml配置文件,
# 使用参数或配置文件的效果是等价的
# 在根目录blog-yoli下新建pagefind.yml配置文件,添加保存以下规则:

# 索引目录
site: public # hugo渲染后页面的保存目录
output-path: search
excerptLength: 200
exclude_selectors:
  - "div.tag-cloud-tags" # class为tag-cloud-tags的div标签
  - "div.categories-table"
  - "div.page.archive"
  - "div.single-title.animate__animated.animate__pulse.animate__faster"
  - "select .color-theme-select"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash

# 运行 Hugo
hugo

# Download pagefind binary
wget -O pagefind.tar.gz https://github.com/CloudCannon/pagefind/releases/download/v1.0.4/pagefind_extended-v1.0.4-x86_64-unknown-linux-musl.tar.gz

# 解压
tar -xzvf pagefind.tar.gz -C ./
chmod +x ./pagefind_extended

# 运行 pagefind
./pagefind_extended

构建配置: “构建命令”: chmod +x deploy.sh&&./deploy.sh
“构建输出”: public
“根目录”:
“构建注释”: 已启用

凭记忆写的半年前的折腾过程,另可参考https://www.xiaoledeng.com/2024/01/13/hugo-set-pagefind-local-search-3/