I don’t like code redundancy, so I wanted to create convention for sharing snippets between language versions of the posts (because code is always in English πŸ˜‰). As it turned out, it’s not that obvious in Hugo.

Research on this matter

It would seem that the matter is very simple: we create a directory, refer to the snippets from each language version, display the same in each one, and after making any changes in one place, we see the effect in each. Well, not really πŸ˜‰

I’ve tried many approaches, from headless bundles, through leaf bundles, to shortcodes with .Site.GetPage usage (as I found in several articles). There always were problems, and I think it’s related to chosen translation by content directory convention.

When I was starting to think about changing convention and throwing everything into one content directory (and using *.<lang>.md for multi-language support), I stumbled upon one Hugo’s built-in function: readFile. Finally it was possible to refer files from the outside of contentDir.

Snippet implementation

I went with such file structure:

hugo/
β”œβ”€ content/
β”‚  β”œβ”€ _snippets/
β”‚  β”‚  β”œβ”€ 2022/
β”‚  β”‚  β”‚  β”œβ”€ 04/
β”‚  β”‚  β”‚  β”‚  β”œβ”€ some-post/
β”‚  β”‚  β”‚  β”‚  β”‚  β”œβ”€ snippet1.md
β”‚  β”‚  β”‚  β”‚  β”‚  β”œβ”€ snippet2.md
β”‚  β”œβ”€ en/
β”‚  β”‚  β”œβ”€ 2022/
β”‚  β”‚  β”‚  β”œβ”€ 04/
β”‚  β”‚  β”‚  β”‚  β”œβ”€ some-post.md
β”‚  β”œβ”€ pl/
β”‚  β”‚  β”œβ”€ 2022/
β”‚  β”‚  β”‚  β”œβ”€ 04/
β”‚  β”‚  β”‚  β”‚  β”œβ”€ jakis-post.md

Next, I’ve created shortcode for rendering code snippets:

<!-- layouts/shortcodes/snippet.html -->

{{ $path := (printf "/content/_snippets/%s" (.Get 0))}}

{{ if eq (path.Ext $path) "" }}
    {{ $path = (printf "%s.md" $path)}}
{{ end }}

{{ if os.FileExists (path.Clean $path) }}
    {{ $page := os.ReadFile (path.Clean $path) }}

    {{ $page | markdownify }}
{{ else }}
    <div class="banner banner-danger">{{ i18n "invalid_snippet_reference" }}</div>
{{ end }}

Thanks to it, in posts I can do this:

{{</* snippet "2022/04/some-post/snippet1" */>}}

{{</* snippet "2022/04/some-post/snippet2.md" */>}}

The advantage of this approach is also the fact, that in future posts I will be able to refer to the code used previously, by including a selected snippet without having to duplicate the code in another file. Are there cons? It will turn out in practice πŸ˜