You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hugo集成Lunr.js无法索引Front Matter Sections内容的解决问询

解决Hugo集成Lunr.js时Front Matter中banner和product_info内容未被索引的问题

要将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 13:43:17