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

如何在Hugo中插入带tag指定内容的AsciiDoc文件?

解决Hugo中AsciiDoc文档合并与链接问题

一、支持Tag提取的自定义短码

原短码仅能读取完整文件,要实现类似Asciidoctor中include::chapter01.adoc[tag=main]的指定区块提取功能,可创建如下自定义短码(保存为layouts/shortcodes/asciidoc-include.html):

{{ $filePath := printf "%s%s" .Page.File.Dir (.Get 0) }}
{{ $content := readFile $filePath }}
{{/* 移除文件开头的YAML头部 */}}
{{ $cleanContent := replaceRE "^---[\\s\\S]+?---" "" $content }}
{{/* 处理tag参数,提取对应区块 */}}
{{ if .Get "tag" }}
  {{ $tag := .Get "tag" }}
  {{ $startMarker := printf "^\\[tag=%s\\]" $tag }}
  {{ $endMarker := "^\\[endtag\\]" }}
  {{/* 匹配tag和endtag之间的内容 */}}
  {{ $tagContent := findRE (printf "%s[\\s\\S]+?%s" $startMarker $endMarker) $cleanContent 1 | default (slice $cleanContent) }}
  {{/* 移除标记并清理空行 */}}
  {{ $finalContent := index $tagContent 0 | replaceRE $startMarker "" | replaceRE $endMarker "" | trim }}
  {{ $finalContent | safeHTML }}
{{ else }}
  {{/* 无tag时输出整个文件内容 */}}
  {{ $cleanContent | safeHTML }}
{{ end }}

使用方式:

  • 提取指定tag内容:{{< asciidoc-include chapter01.adoc tag=main >}}
  • 读取完整文件:{{< asciidoc-include chapter01.adoc >}}

二、处理AsciiDoc内置include::语法

Hugo默认不解析AsciiDoc原生的include::语法,可通过两种方案解决:

  • 预编译合并:在Hugo构建前,用asciidoctor命令将包含include::的主文档编译为完整的AsciiDoc文件,再交由Hugo处理。
  • 短码递归解析:扩展上述短码,添加解析include::语法的逻辑,递归读取并替换包含的文件(需注意避免循环引用)。

三、修复xref链接失效问题

AsciiDoc原生xref生成的链接路径不符合Hugo路由规则,可通过以下方式修复:

  • 统一文档文件名与Hugo生成的slug,确保xref目标能匹配到正确的HTML路径。
  • 替换原生xref为Hugo的ref/relref短码,例如将xref:chapter01.adoc#section1[]改为{{< ref "chapter01#section1" >}}。
  • 自定义Asciidoctor扩展,在编译阶段自动将xref转换为Hugo兼容的链接格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:55:05