Am I right in the assumption that there is currently no way to generate a global, say JS, resource that differs per language?[1]
Because
Hugo’s asset pipeline around global resources is not meant to produce output that differs per page; instead, everything gets aggressively cached, which means a template under assets/ is built only for the first (default) language and recycled afterwards.
Global resources can only be loaded from the assets/ dir, thus we can’t resort to a regular layout file – only resources can be fed to js.Build.
Page resources are also not what we’re looking for since the resource would need to exist in every page bundle (but we want to use a global resource).
I had also no success with trying to duplicate the global resource for every language and suffixing it with the respective language identifier.
Any plans on lifting this limitation?
The actual issue this came up with is found here. ↩︎
{{ with resources.Get (printf "js/main.%s.js" .Language.Lang) }}
{{ if eq hugo.Environment "development" }}
{{ with . | js.Build }}
<script src="{{ .RelPermalink }}"></script>
{{ end }}
{{ else }}
{{ $opts := dict "minify" true }}
{{ with . | js.Build $opts | fingerprint }}
<script src="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous"></script>
{{ end }}
{{ end }}
{{ end }}
Here’s a working example. Open the browser console and switch back and forth between the two languages.
git clone --single-branch -b hugo-forum-topic-46212 https://github.com/jmooring/hugo-testing hugo-forum-topic-46212
cd hugo-forum-topic-46212
hugo server
Initially I thought language-suffixed assets wouldn’t be acceptable for my use case since I would need to know all the languages in advance, i.e. create the assets by hand.
Now I realized that I can accomplish what I want indirectly with
a sentinel like REPLACE-ME-WITH-LANG-PREFIX in assets/js/flexsearch.js
Since the above is quite an unintuitive way (one might call it “workaround”) to convince Hugo to cache an asset file per language instead of per whole site, I wonder:
Are there any plans on allowing more control over assets resource caching behaviour? So I could put the lang-specific template logic directly in the asset file instead of the template that calls resources.ExecuteAsTemplate on it?
Damn, this is almost what I tried first, but I was muddled enough to not vary the target path for the resource created by ExecuteAsTemplate. Only the english version was generated (with a long hash in the filename), so I (falsely) assumed that it would get executed only once and used from cache for subsequent langs and there would nothing I could do about it. It was indeed executed only once (or at least only a single file was generated instead of one per language), but simply because I’m a fool.