Hugo 短代碼實作:bundle-file(多語言檔案與附件放在同一個 Page Bundle 目錄)

使用自訂 bundle-file 短代碼,在當前語言資源缺失時自動回退到其他翻譯頁面,統一輸出附件下載連結。

在多語言網站中,文章正文通常會共用同一份附件(例如 PDF、設定檔、腳本)。 如果每個語言版本都手動維護下載連結,後期很容易出現連結不一致或檔案遺失。

這篇文章提供一個可直接複用的 Hugo 短代碼 bundle-file,用來解決這個問題。

目標

將同一篇文章的多語言檔案與附件放在同一個 Page Bundle 目錄中,例如:

1
2
3
4
5
6
content/post/2026/03/09/01/
  index.zh-cn.md
  index.zh-tw.md
  index.en.md
  demo.pdf
  script.sh

這樣可以最大化資源複用,減少重複拷貝。 Hugo 轉成 HTML 後,希望多個語言都指向同一份附件,不重複拷貝。

短代碼實作

檔案:layouts/shortcodes/bundle-file.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{{- $name := .Get "name" -}}
{{- $text := .Get "text" | default $name -}}

{{- $res := .Page.Resources.GetMatch $name -}}
{{- if not $res -}}
  {{- range .Page.AllTranslations -}}
    {{- if not $res -}}
      {{- $tmp := .Resources.GetMatch $name -}}
      {{- if $tmp }}{{ $res = $tmp }}{{ end -}}
    {{- end -}}
  {{- end -}}
{{- end -}}

{{- if $res -}}
<a href="{{ $res.RelPermalink }}">{{ $text }}</a>
{{- else -}}
<span>Missing file: {{ $name }}</span>
{{- end -}}

bundle-file 的行為很簡單:

  1. 優先從當前頁面的資源中查找檔案。
  2. 當前語言找不到時,到其他翻譯頁面繼續查找同名檔案。
  3. 找到後輸出下載連結,找不到則提示缺失檔名。

參數說明

  • name:附件檔名,必填。
  • text:連結顯示文字,可選;不傳時預設顯示 name

使用示例

1
Missing file: demo.pdf

不傳 text 時:

1
Missing file: demo.pdf

發佈前檢查

  1. 附件與文章位於同一個 Page Bundle。
  2. name 與真實檔名完全一致(含大小寫)。
  3. 本地預覽點擊連結,確認可訪問。

總結

bundle-file 讓多語言文章的附件連結管理從「手動維護路徑」,變成「按規則自動查找」。 對長期維護的知識庫或技術部落格來說,這能顯著降低連結錯誤率,也能減少發佈前排查成本。

记录并分享
使用 Hugo 建立
主題 StackJimmy 設計