博客搭建三:hugo添加搜索功能

博客搭建逐渐完善,博文内容也逐渐增多,添加搜索功能可以很方便的检索内容,对知识进行回顾,温故而知新。

​实现hugo博客的内容检索利用的是algolia服务,首先,修改博客根目录下的 config.toml文件(而非主题文件下的,不然无法生成.josn文件),添加以下内容(粘贴至末尾即可):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[outputs]
  home = ["HTML","RSS","TXT","Algolia"]
  section = ["HTML"]
  taxonomy = ["HTML"]
  term = ["HTML"]

[outputFormats.Algolia]
  mediaType = "application/json"
  baseName = "algolia"
  isPlainText = true

在博客根目录/layouts创建_default文件夹,在该文件夹内创建list.algolia.json文件,用nop++或者其他软件打开该文件并添加以下内容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[
  {{- range $index, $entry := .Site.RegularPages }}
  {{- if $index }}, {{ end }}
  {
    "objectID": {{ .File.TranslationBaseName }},
    "url": {{ .Permalink | jsonify }},
    "title": {{ .Title | jsonify }},
    "summary": {{ .Summary | jsonify }},
    "content": {{ .Plain | jsonify }},
    "pubDate": {{ .PublishDate | jsonify }}
  }
  {{- end }}
]

注册algolia

按照注册指引流程走完然后打开设置,见下图。 博客搭建三1

博客搭建三2

 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
# Search config
  # 搜索配置
  [params.search]
    enable = true
    # type of search engine ["lunr", "algolia"]
    # 搜索引擎的类型 ["lunr", "algolia"]
    type = "algolia"
    # max index length of the chunked content
    # 文章内容最长索引长度
    contentLength = 4000
    # placeholder of the search bar
    # 搜索框的占位提示语
    placeholder = "So一下"
    # max number of results length
    # 最大结果数目
    maxResultLength = 10
    # snippet length of the result
    # 结果内容片段长度
    snippetLength = 30
    # HTML tag name of the highlight part in results
    # 搜索结果中高亮部分的 HTML 标签
    highlightTag = "em"
    # whether to use the absolute URL based on the baseURL in search index
    # 是否在搜索索引中使用基于 baseURL 的绝对路径
    absoluteURL = false
    [params.search.algolia]
      index = "blog"
      appID = "xxx" # 你的密钥
      searchKey = "xxx" # 你的密钥

在博客根目录输入cmd命令:

1
hugo

然后会在public文件夹下生成algolia.json文件,我们需要将该文件提交到algolia,见下图。 博客搭建三3 博客搭建三4

至此初步搜索功能已经具备了(见下图),能够满足日常使用需求,另外algolia免费版每月有10000次搜索体验。但是这样每次更新博客内容都需要手动提交algolia.json,才能搜索到新内容,也可以设置自动提交,可自行搜索相关设置。 博客搭建三5

Licensed under CC BY-NC-SA 4.0
© ziyue.tech版权所有
Built with Hugo
主题 OoO落墨灼夭 设计

本站访问量:   您是本站第 位访问者