Skip to main content

Hugo 在 figcaption 使用 footnote

如何在 Hugo SSG 中,在圖片的文字描述中使用註腳 footnote 呢?也就是說在 figcaption 使用 footnote,比如

![](/img/04.webp "foo[^123]")

[^123]: bar

答案

不可能,Hugo 使用 Goldmark 解析 Markdown,而 Goldmark 直接把圖片的文字敘述以純文字處理,不會再放回 AST 節點處理1

唯一的解法是使用 shortcode,首先你要自建一個 layouts/_shortcodes/fig.html shortcode,內容如下

<figure {{ with .Get "class" }}class="{{ . }}"{{ end }}>
{{- $u := urls.Parse (.Get "src") -}}
{{- $src := $u.String -}}
{{- if not $u.IsAbs -}}
{{- with or (.Page.Resources.Get $u.Path) (resources.Get $u.Path) -}}
{{- $src = .RelPermalink -}}
{{- end -}}
{{- end -}}

<img src="{{ $src }}" loading="lazy"
{{- if .Get "alt" }} alt="{{ with .Get "alt" }}{{ . }}{{ end }}"{{- end -}}>
{{- if .Get "title" -}}
<figcaption>
{{- with (.Get "title") -}}
{{ printf "\n\n%s\n\n" . }}
{{- end -}}
</figcaption>
{{- end -}}
</figure>

並且搭配 Markdown notation 使用

{{% fig
attr="class='center-cap center-img' style='width:50%'"
src="/img/04.webp"
alt="alt"
title="1234[^fn_a]"
%}}

[^fn_a]: Footnote text.

還要啟用 renderer.unsafe

原理是透過 Markdown notation 把 shortcode 的 HTML 內容丟到 Markdown 讓 Goldmark 一次處理,關鍵在於 {{ printf "\n\n%s\n\n" . }} 增加換行避免和 HTML 標籤相連,這樣 caption 內容才能被辨識成 Markdown 區塊,最後和整份 Markdown 一起渲染。

簡單來說就是所有東西都是 HTML,只有 figcaption 區域故意加上空白讓他被當作 Markdown 處理,是一個 tricky 的做法。

Footnotes

  1. https://github.com/yuin/goldmark/blob/6ed00da2d6d53d831827e54ee5d334f4544693b9/renderer/html/html.go#L626-L630