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

如何生成Hugo自定义文章链接,跳转至摘要后的指定内容位置

解决方案:Hugo生成指向文章特定位置的“阅读全文”链接

场景1:默认摘要(前70个单词)→ 跳转到第71词所在位置

要实现这个需求,需要分两步处理:在文章内容里给目标位置插入锚点,再在列表页生成带锚点的跳转链接。

  1. 文章模板(如layouts/_default/single.html)插入锚点
    利用Hugo的模板函数把内容拆成单词数组,在第71个单词前插入空锚点标签:

    {{ $content := .Content }}
    {{ $words := split $content " " }}
    {{ if ge (len $words) 71 }}
      {{ $modifiedContent := slice }}
      {{ range $index, $word := $words }}
        {{ if eq $index 70 }} <!-- 第71个单词的索引是70(从0开始计数) -->
          {{ $modifiedContent = $modifiedContent | append "<span id=\"continue-point\"></span>" }}
        {{ end }}
        {{ $modifiedContent = $modifiedContent | append $word }}
      {{ end }}
      {{ delimit $modifiedContent " " | safeHTML }}
    {{ else }}
      {{ $content }}
    {{ end }}
    
  2. 列表页(如layouts/_default/list.html)生成带锚点的链接
    把原来的永久链接改成带锚点的形式:

    <a href="{{ .RelPermalink }}#continue-point">阅读全文</a>
    

场景2:摘要为第一段 → 跳转到第二段开头

这种场景逻辑更直接,给文章第二段手动加锚点即可:

  1. 文章模板给第二段加ID
    把内容按段落拆分,给第二段的<p>标签加上锚点ID:

    {{ $paragraphs := split .Content "</p>" }}
    {{ $modifiedContent := slice }}
    {{ range $index, $p := $paragraphs }}
      {{ if ne $p "" }}
        {{ if eq $index 1 }} <!-- 第二段的索引是1(第一段为0) -->
          {{ $modifiedContent = $modifiedContent | append (printf "<p id=\"start-from-second\">%s</p>" (trim $p "<p>")) }}
        {{ else }}
          {{ $modifiedContent = $modifiedContent | append (printf "<p>%s</p>" (trim $p "<p>")) }}
        {{ end }}
      {{ end }}
    {{ end }}
    {{ delimit $modifiedContent "" | safeHTML }}
    
  2. 列表页链接指向第二段锚点

    <a href="{{ .RelPermalink }}#start-from-second">阅读全文</a>
    

额外优化提示

  • 可以把锚点处理逻辑封装成短代码或部分模板,避免在多个模板里重复写代码。
  • 如果担心空格分割单词的精度问题(比如标点和单词粘连),可以用findRE函数匹配纯单词:{{ $words := findRE "\w+" .Content }},拆分更准确。
  • 可给锚点加个视觉提示,比如给<span id="continue-point">加个小箭头样式,让读者清晰看到跳转位置。

内容的提问来源于stack exchange,提问作者Duck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:57:48