用Algolia给Hugo博客加个搜索功能,轻松搞定!
编辑你是不是也想过给自己的博客加个搜索功能?找来找去,发现Algolia是个不错的选择,不仅简单易用,还能免费白嫖!每个月可以搜索10000次,对于个人博客来说,完全够用了。今天就来教你如何用Algolia实现Hugo博客的搜索功能。
第一步:生成搜索数据
1. 修改配置文件
首先,我们需要让Hugo生成一个包含博客内容的JSON文件,供Algolia使用。打开config.toml
文件,添加以下配置:
[outputs]
home = ["HTML", "RSS", "Algolia"]
[outputFormats.Algolia]
baseName = "algolia"
isPlainText = true
mediaType = "application/json"
notAlternative = true
这段配置告诉Hugo在生成网站时,同时生成一个algolia.json
文件。
2. 添加模板文件
接下来,我们需要创建一个模板文件,告诉Hugo如何生成这个JSON文件。在/layouts/_default/
目录下创建一个list.algolia.json
文件,内容如下:
{{/* 生成Algolia搜索索引文件 */}}
{{- $.Scratch.Add "index" slice -}}
{{/* content/posts或content/post目录下的博文才生成索引 */}}
{{- range where (where .Site.Pages "Type" "in" (slice "posts" "post")) "IsPage" true -}}
{{- if and (not .Draft) (not .Params.private) -}}
{{- $.Scratch.Add "index" (dict "objectID" .File.UniqueID "url" .Permalink "content" (.Summary | plainify) "tags" .Params.Tags "lvl0" .Title "lvl1" .Params.Categories "lvl2" "摘要") -}}
{{- end -}}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}
这个模板会遍历你的博客文章,生成一个包含文章标题、链接、摘要等信息的JSON文件。
3. 生成数据文件
配置好模板后,运行hugo
命令,Hugo就会生成一个algolia.json
文件。这个文件包含了你的博客内容,稍后我们会把它上传到Algolia。
第二步:在Algolia中创建索引
1. 注册Algolia账号
首先,去Algolia官网注册一个账号。注册完成后,登录进入控制台。
2. 创建应用程序
在Algolia控制台中,点击“Create Application”按钮,创建一个新的应用程序。选择免费套餐,足够个人博客使用了。
3. 创建索引
在应用程序中,点击“Indices”选项卡,创建一个新的索引。这个索引将用来存储你的博客数据。
4. 导入数据
你可以通过Algolia提供的API将algolia.json
文件中的数据推送到索引中,也可以手动上传。上传完成后,Algolia就会开始处理这些数据,准备提供搜索服务。
5. 配置搜索属性
在索引设置中,你可以配置哪些字段可以被搜索。比如,你可以设置标题、摘要、标签等字段为可搜索的。
6. 配置排序规则
你还可以设置搜索结果的排序规则,比如按发布时间、阅读量等排序。
第三步:在博客中添加搜索功能
1. 创建搜索页面
在你的Hugo博客中,创建一个新的页面来展示搜索框和搜索结果。比如,可以在content/search.md
中创建一个搜索页面。
<h3>搜索</h3>
<div id="searchbox"></div>
<hr>
<div id="hits"></div>
<div id="pagination"></div>
2. 引入样式和脚本
为了让搜索页面看起来更美观,你可以引入Algolia提供的样式和JavaScript库。
<!-- 引入基本样式 -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch.min.css">
<!-- 引入主题样式 -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch-theme-algolia.min.css">
<!-- 引入InstantSearch.js库 -->
<script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.6.0/dist/instantsearch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
3. 编写搜索脚本
最后,编写一段JavaScript代码来初始化搜索功能。
<div id="search-searchbar"></div>
<div class="post-list" id="search-hits"></div>
<script>
const searchClient = algoliasearch('你的ApplicationID', '你的SearchOnlyAPIKey');
const search = instantsearch({
indexName: '你的索引名称',
searchClient,
});
search.addWidgets([
instantsearch.widgets.searchBox({
container: '#searchbox',
}),
instantsearch.widgets.hits({
container: '#hits',
})
]);
search.start();
</script>
记得替换你的ApplicationID
、你的SearchOnlyAPIKey
和你的索引名称
为你在Algolia中获取的实际值。
大功告成!
现在,你的博客就有了一个强大的搜索功能!用户可以轻松搜索到你博客中的内容,体验大大提升。赶紧试试吧,相信你会爱上这个功能的!
如果你觉得这篇文章对你有帮助,别忘了分享给你的朋友们哦!
- 0
- 0
-
分享