Hugo Shortcode Practice: bundle-file (Keep Multilingual Files and Attachments in One Page Bundle)

Use a custom bundle-file shortcode to automatically fall back to other translations when the current language resource is missing, and output a unified attachment link.

In multilingual sites, posts often share the same attachment files (for example, PDFs, config files, or scripts). If each language version maintains download links manually, link drift and missing files become common over time.

This article introduces a reusable Hugo shortcode, bundle-file, to solve this problem.

Goal

Keep multilingual post files and attachments in the same Page Bundle directory, for example:

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

This maximizes reuse and avoids duplicate copies. After Hugo builds HTML pages, all language versions should point to the same attachment instead of duplicated files.

Shortcode Implementation

File: 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 works with a simple strategy:

  1. Look up the file in current page resources first.
  2. If not found, search the same file name in other translated pages.
  3. Output a download link when found, or show a missing-file message when not found.

Parameters

  • name: attachment filename (required)
  • text: link label (optional); defaults to name

Usage Example

1
Missing file: demo.pdf

Without text:

1
Missing file: demo.pdf

Pre-publish Checklist

  1. Put attachments and post files in the same Page Bundle.
  2. Ensure name exactly matches the real filename (including case).
  3. Click links in local preview to confirm accessibility.

Summary

bundle-file turns multilingual attachment handling from manual path maintenance into rule-based automatic lookup. For long-lived knowledge bases and technical blogs, this reduces broken-link risk and pre-release review time.

记录并分享
Built with Hugo
Theme Stack designed by Jimmy