Hugo集成Lunr.js无法索引Front Matter Sections内容的解决问询
要将Front Matter中的banner和product_info区域内容加入Lunr.js的搜索索引,需要修改索引生成逻辑,把这些自定义字段的文本内容合并到索引的content字段中。以下是具体修改步骤:
1. 修改index.html中的window.store(直接给Lunr提供数据)
原代码中content仅包含文章主体内容,现在需要拼接banner、product_info及子字段的文本内容:
<script> window.store = { {{ range .Site.Pages }} "{{ .Permalink }}": { "title": "{{ .Title }}", "tags": [{{ range .Params.Tags }}"{{ . }}",{{ end }}], "content": {{ (print // 拼接banner的标题和内容 (with .Params.banner; .title " " .content; end) // 拼接product_info的标题、内容及所有features的内容 (with .Params.product_info; .title " " .content (range .features; .content " "; end); end) // 保留原文章主体内容 .Content ) | plainify | jsonify }}, "url": "{{ .Permalink }}" }, {{ end }} } </script>
关键说明:
- 使用
with判断字段是否存在,避免无该字段的页面出现空值或错误 print将所有需要索引的文本拼接成一个字符串plainify移除所有HTML/Markdown格式,转为纯文本jsonify确保内容是合法的JSON字符串,避免引号冲突
2. 修改layouts/default/index.json(若使用JSON索引源)
如果你的搜索逻辑依赖JSON索引文件,同样需要更新contents字段:
{{ $.Scratch.Add "index" slice }} {{ range site.RegularPages }} {{ $date:= time.Format ":date_long" .PublishDate }} {{ with .Params.image }} {{ if (fileExists (add `assets/` .)) }} {{ $image:= resources.Get . }} {{ $image:= $image.Resize "650x" }} {{ $.Scratch.Set "image" $image.Permalink }} {{ end }} {{ end }} {{ $image:= $.Scratch.Get "image" }} {{ $.Scratch.Add "index" (dict "title" .Title "date" $date "image" $image "categories" .Section "contents" (print (with .Params.banner; .title " " .content; end) (with .Params.product_info; .title " " .content (range .features; .content " "; end); end) .Plain ) "permalink" .RelPermalink) }} {{ end }} {{ $.Scratch.Get "index" | jsonify }}
3. 验证效果
修改完成后,重新生成站点(hugo命令),查看生成的index.html或index.json文件,确认banner和product_info的内容已被包含在content字段中。此时Lunr.js就能索引到这些Front Matter区域的内容了。
内容的提问来源于stack exchange,提问作者isin
相关产品推荐
相关产品推荐

