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 π