建站第十三篇 Hugo博客實(shí)現(xiàn)輕量級(jí)搜索功能

Hugo是由Go語言實(shí)現(xiàn)的靜態(tài)網(wǎng)站生成器。簡單、易用、高效、易擴(kuò)展、快速部署。靜態(tài)站點(diǎn)無法自帶動(dòng)態(tài)搜索功能,但作為一個(gè)博客,隨著文章漸漸增多,站內(nèi)搜索功能還是必要的。

選擇

針對(duì)這項(xiàng)需求,Hugo官方推薦了一些開源和商業(yè)站內(nèi)搜索方案Search for your Hugo Website 。 本博客使用的Hugo主題是Clean White Theme for Hugo, 已經(jīng)支持接入Algolia。Algolia是一家提供第三方搜索服務(wù)的公司,他們提供了免費(fèi)易用的搜索服務(wù),讓開發(fā)者可以快速對(duì)站內(nèi)內(nèi)容進(jìn)行檢索和搜索。對(duì)于我來說,Algolia存在幾個(gè)不能忍的問題:

  • 國內(nèi)使用速度慢,因?yàn)樗蟹?wù)器均位于海外;
  • 第三方服務(wù)需要注冊(cè),且存在依賴;
  • 更新文章時(shí)需要npm重新生成索引,對(duì)build工具多了一項(xiàng)要求,不清爽。

出于以上的考慮,我決定放棄Algolia,尋找更輕的解決方案。依然從官方推薦的方案中選擇, Github Gist for Fuse.js integration 成為了我首選的方案,原因如下:

  • 最重要的原因,作者3天前還在討論區(qū)進(jìn)行解答,是個(gè)可靠的coder;
  • 不需要 Hugo 以外, npm、grunt 或者其它build工具;
  • 借助Fuse.js生成索引,相對(duì)輕。

Fuse.js 是一個(gè)功能強(qiáng)大、輕量級(jí)的模糊搜索庫,通過提供簡單的 api 調(diào)用,達(dá)到強(qiáng)大的模糊搜索效果,無需搞懂復(fù)雜的模糊搜索算法。

實(shí)踐

Github Gist for Fuse.js integration 的文檔所說,實(shí)現(xiàn)使用這個(gè)插件,只需要增加一些文件和修改config.toml中的output格式。整個(gè)過程我整理一下。

添加文件

在hugo項(xiàng)目根目錄添加4個(gè)文件: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中,添加以下內(nèi)容

[outputs]
home = ["HTML", "RSS", "JSON"]

如果已經(jīng)存在 [outputs]這項(xiàng),就在home中增加"JSON"格式。

按說明完成之后,訪問localhost:1313/search就應(yīng)該看到搜索框效果了。但是我的搜索頁并沒有看到搜索框。

哪里出了問題?

改造

一般說來,layouts/目錄里保存的是 Hugo 的模板文件。layouts/是站點(diǎn)級(jí)別的模板, themes/<theme name>/layouts/是主題級(jí)別的模板,站點(diǎn)級(jí)別模板的設(shè)置優(yōu)先于主題級(jí)別的模板。而我使用的主題Clean White Theme for Hugo ,在這里主題模版設(shè)置優(yōu)先于站點(diǎn)模版設(shè)置,我們可以稍加改造,使主題模版失效就可以了。

先找到主題對(duì)應(yīng)的/search落地頁,是位于主題目錄下的layouts/search/list.html。我們只需要將list.html改個(gè)名字,就達(dá)到了主題模版失效的目的。

另外還要將配置文件中的algolia配置關(guān)掉。為此,要對(duì)主題目錄下的layouts/partials/nav.html進(jìn)行修改。

原版

 {{ 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 }}

同時(shí)在config.toml中添加配置參數(shù)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這個(gè)名字,所以需要我們修改一下布局頁baseof.html,位于主題目錄下layouts/_default/baseof.html。

......
{{ block "main" . }}
{{ end }}

{{ partial "footer.html" . }}
......

block mainpartial footer 之間加入block footerfiles

......
{{ block "main" . }}
{{ end }}

{{ block "footerfiles" . }}
{{ end }}

{{ partial "footer.html" . }}
......

至此,改造完成。

效果

image.png

參考文章

  1. 《Hugo JS Searching with Fuse.js》,https://gist.github.com/eddiewebb/735feb48f50f0ddd65ae5606a1cb41ae
  2. 《為 Hugo 添加搜索功能》,https://blog.humblepg.com/post/2019/06/hugo-search.html
  3. 《Search for your Hugo Website》,https://gohugo.io/tools/search/
  4. 《What is Fuse.js?》,https://fusejs.io/?from=thosefree.com
image.png

本作品由 IvyWooo 采用知識(shí)共享署名-非商業(yè)性使用-相同方式共享 4.0 國際許可協(xié)議 進(jìn)行許可,轉(zhuǎn)載請(qǐng)注明出處。 本文鏈接

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容