Hugo是由Go语言实现的静态网站生成器。简单、易用、高效、易扩展、快速部署。静态站点无法自带动态搜索功能,但作为一个博客,随着文章渐渐增多,站内搜索功能还是必要的。
选择
针对这项需求,Hugo官方推荐了一些开源和商业站内搜索方案Search for your Hugo Website 。 本博客使用的Hugo主题是Clean White Theme for Hugo, 已经支持接入Algolia。Algolia是一家提供第三方搜索服务的公司,他们提供了免费易用的搜索服务,让开发者可以快速对站内内容进行检索和搜索。对于我来说,Algolia存在几个不能忍的问题:
- 国内使用速度慢,因为所有服务器均位于海外;
- 第三方服务需要注册,且存在依赖;
- 更新文章时需要
npm
重新生成索引,对build工具多了一项要求,不清爽。
出于以上的考虑,我决定放弃Algolia,寻找更轻的解决方案。依然从官方推荐的方案中选择, Github Gist for Fuse.js integration 成为了我首选的方案,原因如下:
- 最重要的原因,作者3天前还在讨论区进行解答,是个可靠的coder;
- 不需要 Hugo 以外, npm、grunt 或者其它build工具;
- 借助Fuse.js生成索引,相对轻。
Fuse.js 是一个功能强大、轻量级的模糊搜索库,通过提供简单的 api 调用,达到强大的模糊搜索效果,无需搞懂复杂的模糊搜索算法。
实践
按Github Gist for Fuse.js integration 的文档所说,实现使用这个插件,只需要增加一些文件和修改config.toml中的output格式。整个过程我整理一下。
添加文件
在hugo项目根目录添加4个文件:content/search.md
,layouts/_default/search.html
, static/js/search.js
,layouts/_default/index.json
content/search.md
---
title: "Search Results"
sitemap:
priority : 0.1
layout: "search"
---
This file exists solely to respond to /search URL with the related `search` layout template.
No content shown here is rendered, all content is based in the template layouts/page/search.html
Setting a very low sitemap priority will tell search engines this is not important content.
This implementation uses Fusejs, jquery and mark.js
## Initial setup
Search depends on additional output content type of JSON in config.toml
\```
[outputs]
home = ["HTML", "JSON"]
\```
## Searching additional fileds
To search additional fields defined in front matter, you must add it in 2 places.
### Edit layouts/_default/index.JSON
This exposes the values in /index.json
i.e. add `category`
\```
...
"contents":{{ .Content | plainify | jsonify }}
{{ if .Params.tags }},
"tags":{{ .Params.tags | jsonify }}{{end}},
"categories" : {{ .Params.categories | jsonify }},
...
\```
### Edit fuse.js options to Search
`static/js/search.js`
\```
keys: [
"title",
"contents",
"tags",
"categories"
]
\```
layouts/_default/search.html
{{ define "footerfiles" }}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.0/fuse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js"></script>
<script src="{{ "js/search.js" | absURL }}"></script>
{{ end }}
{{ define "main" }}
<section class="resume-section p-3 p-lg-5 d-flex flex-column">
<div class="my-auto" >
<form action="{{ "search" | absURL }}">
<input id="search-query" name="s"/>
</form>
<div id="search-results">
<h3>Matching pages</h3>
</div>
</div>
</section>
<!-- this template is sucked in by search.js and appended to the search-results div above. So editing here will adjust style -->
<script id="search-result-template" type="text/x-js-template">
<div id="summary-${key}">
<h4><a href="${link}">${title}</a></h4>
<p>${snippet}</p>
${ isset tags }<p>Tags: ${tags}</p>${ end }
${ isset categories }<p>Categories: ${categories}</p>${ end }
</div>
</script>
{{ end }}
static/js/search.js
summaryInclude=60;
var fuseOptions = {
shouldSort: true,
includeMatches: true,
threshold: 0.0,
tokenize:true,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
{name:"title",weight:0.8},
{name:"contents",weight:0.5},
{name:"tags",weight:0.3},
{name:"categories",weight:0.3}
]
};
var searchQuery = param("s");
if(searchQuery){
$("#search-query").val(searchQuery);
executeSearch(searchQuery);
}else {
$('#search-results').append("<p>Please enter a word or phrase above</p>");
}
function executeSearch(searchQuery){
$.getJSON( "/index.json", function( data ) {
var pages = data;
var fuse = new Fuse(pages, fuseOptions);
var result = fuse.search(searchQuery);
console.log({"matches":result});
if(result.length > 0){
populateResults(result);
}else{
$('#search-results').append("<p>No matches found</p>");
}
});
}
function populateResults(result){
$.each(result,function(key,value){
var contents= value.item.contents;
var snippet = "";
var snippetHighlights=[];
var tags =[];
if( fuseOptions.tokenize ){
snippetHighlights.push(searchQuery);
}else{
$.each(value.matches,function(matchKey,mvalue){
if(mvalue.key == "tags" || mvalue.key == "categories" ){
snippetHighlights.push(mvalue.value);
}else if(mvalue.key == "contents"){
start = mvalue.indices[0][0]-summaryInclude>0?mvalue.indices[0][0]-summaryInclude:0;
end = mvalue.indices[0][1]+summaryInclude<contents.length?mvalue.indices[0][1]+summaryInclude:contents.length;
snippet += contents.substring(start,end);
snippetHighlights.push(mvalue.value.substring(mvalue.indices[0][0],mvalue.indices[0][1]-mvalue.indices[0][0]+1));
}
});
}
if(snippet.length<1){
snippet += contents.substring(0,summaryInclude*2);
}
//pull template from hugo templarte definition
var templateDefinition = $('#search-result-template').html();
//replace values
var output = render(templateDefinition,{key:key,title:value.item.title,link:value.item.permalink,tags:value.item.tags,categories:value.item.categories,snippet:snippet});
$('#search-results').append(output);
$.each(snippetHighlights,function(snipkey,snipvalue){
$("#summary-"+key).mark(snipvalue);
});
});
}
function param(name) {
return decodeURIComponent((location.search.split(name + '=')[1] || '').split('&')[0]).replace(/\+/g, ' ');
}
function render(templateString, data) {
var conditionalMatches,conditionalPattern,copy;
conditionalPattern = /\$\{\s*isset ([a-zA-Z]*) \s*\}(.*)\$\{\s*end\s*}/g;
//since loop below depends on re.lastInxdex, we use a copy to capture any manipulations whilst inside the loop
copy = templateString;
while ((conditionalMatches = conditionalPattern.exec(templateString)) !== null) {
if(data[conditionalMatches[1]]){
//valid key, remove conditionals, leave contents.
copy = copy.replace(conditionalMatches[0],conditionalMatches[2]);
}else{
//not valid, remove entire section
copy = copy.replace(conditionalMatches[0],'');
}
}
templateString = copy;
//now any conditionals removed we can do simple substitution
var key, find, re;
for (key in data) {
find = '\\$\\{\\s*' + key + '\\s*\\}';
re = new RegExp(find, 'g');
templateString = templateString.replace(re, data[key]);
}
return templateString;
}
layouts/_default/index.json
{{- $.Scratch.Add "index" slice -}}
{{- range .Site.RegularPages -}}
{{- $.Scratch.Add "index" (dict "title" .Title "tags" .Params.tags "categories" .Params.categories "contents" .Plain "permalink" .Permalink) -}}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}
修改toml
Config.toml
在配置文件Config.toml
中,添加以下内容
[outputs]
home = ["HTML", "RSS", "JSON"]
如果已经存在 [outputs]
这项,就在home
中增加"JSON"
格式。
按说明完成之后,访问localhost:1313/search
就应该看到搜索框效果了。但是我的搜索页并没有看到搜索框。
哪里出了问题?
改造
一般说来,layouts/
目录里保存的是 Hugo 的模板文件。layouts/
是站点级别的模板, themes/<theme name>/layouts/
是主题级别的模板,站点级别模板的设置优先于主题级别的模板。而我使用的主题Clean White Theme for Hugo ,在这里主题模版设置优先于站点模版设置,我们可以稍加改造,使主题模版失效就可以了。
先找到主题对应的/search
落地页,是位于主题目录下的layouts/search/list.html
。我们只需要将list.html
改个名字,就达到了主题模版失效的目的。
另外还要将配置文件中的algolia配置关掉。为此,要对主题目录下的layouts/partials/nav.html
进行修改。
原版
{{ if .Site.Params.algolia_search }}
<li>
<a href="{{ "search" | relURL }}"><i class="fa fa-search"></i></a>
</li>
{{ end }}
改成
{{ if .Site.Params.algolia_search }}
<li>
<a href="{{ "search" | relURL }}"><i class="fa fa-search"></i></a>
</li>
{{else if .Site.Params.search}}
<li>
<a href="{{ "search" | relURL }}"><i class="fa fa-search"></i></a>
</li>
{{ end }}
同时在config.toml
中添加配置参数search
[params]
search = true
这里还要注意,官方的search.html
,用名为footerfiles
的block定义了引入的js
{{ define "footerfiles" }}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.0/fuse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js"></script>
<script src="{{ "js/search.js" | absURL }}"></script>
{{ end }}
我的主题中没有在布局中使用footerfiles
这个名字,所以需要我们修改一下布局页baseof.html
,位于主题目录下layouts/_default/baseof.html
。
......
{{ block "main" . }}
{{ end }}
{{ partial "footer.html" . }}
......
在 block main
与 partial footer
之间加入block footerfiles
......
{{ block "main" . }}
{{ end }}
{{ block "footerfiles" . }}
{{ end }}
{{ partial "footer.html" . }}
......
至此,改造完成。
效果
参考文章
- 《Hugo JS Searching with Fuse.js》,https://gist.github.com/eddiewebb/735feb48f50f0ddd65ae5606a1cb41ae
- 《为 Hugo 添加搜索功能》,https://blog.humblepg.com/post/2019/06/hugo-search.html
- 《Search for your Hugo Website》,https://gohugo.io/tools/search/
- 《What is Fuse.js?》,https://fusejs.io/?from=thosefree.com
本作品由 IvyWooo 采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可,转载请注明出处。 本文链接