#14108·hugo

tpl/tplimpl: 为嵌入式链接/图像渲染钩子添加错误处理

作者: gregjotau创建于 2025年11月1日更新于 2026年9月26日
标签ProposalFeature: Render Hookb0

1) 启用/使用嵌入式钩子

toml
# hugo.toml
[markup.goldmark.renderHooks.link]
useEmbedded = "always"  # auto|fallback|never|always
[markup.goldmark.renderHooks.image]
useEmbedded = "always"

这使 Hugo 以与 ref/relref 相同的方式解析 Markdown 目标。([gohugo.io][2])

2) 添加验证并报错的 render-link.html

layouts/_default/_markup/render-link.html:

go-html-template
{{- $u := urls.Parse .Destination -}}
{{- $isAbs := or (ne $u.Scheme "") (strings.HasPrefix .Destination "//") -}}

{{- if not $isAbs -}}
  {{/* 尝试解析内部目标: 页面 → 页面资源 → 全局资源 */}}
  {{- $page := site.GetPage $u.Path | default (.Page.GetPage $u.Path) -}}
  {{- $res  := cond (not $page) (resources.Get $u.Path) nil -}}

  {{- if not (or $page $res) -}}
    {{- errorf "Broken internal link %q on %s" .Destination .Page.File.Path -}}
  {{- end -}}

  {{- if and $page $u.Fragment -}}
    {{- if not ($page.Fragments.Identifiers.Contains $u.Fragment) -}}
      {{- errorf "Broken fragment #%s in link %q on %s" $u.Fragment .Destination .Page.File.Path -}}
    {{- end -}}
  {{- end -}}
{{- end -}}

<a href="{{ .Destination | safeURL }}">{{ .Text | safeHTML }}</a>

注意事项:

  • .Fragments.Identifiers.Contains 可提供可靠的 GitHub 样式…