Skip to content

Instantly share code, notes, and snippets.

@dmuth
Created April 2, 2024 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmuth/faf23a71494cd013157cbdd1bbeca7e0 to your computer and use it in GitHub Desktop.
Save dmuth/faf23a71494cd013157cbdd1bbeca7e0 to your computer and use it in GitHub Desktop.
Painless Concat with Hugo
{{/*
I'm using Hugo to build the front end for https://github.com/dmuth/peco-outage-status
As part of that effort, I'd like to be able to have separate Javascript files thare combined into
a single Javascript file when I build the site.
The good news is that the Concat function in Hugo lets me do this. The bad news is that the key
is the filename, and the contents are cached. This does not lend itself well to rapid development.
So the trick was to create a filename based on the date so that each time a file is edited and Hugo
re-processes its files, a new filename is generated, which results in a cache miss in Concat,
causing a new Javascript file to be created.
Sharing this here in case someone else runs into the same problem as me.
If someone knows of a better way to do this, please tell me. :-)
*/}}
{{ $js_main := resources.Get "js/main.js" }}
{{ $js_current := resources.Get "js/main-current.js" }}
{{ $js_recent := resources.Get "js/main-recent.js" }}
{{/* Make our hash and then only grab the first 6 chars so that the final
filename isn't obscenely long. */}}
{{ $timehash := time.Now.Unix | sha1 }}
{{ $timehash := substr $timehash 0 6 }}
{{ $filename := printf "js/%s.js" $timehash }}
{{ $scripts := slice $js_main $js_current $js_recent | resources.Concat $filename | minify | fingerprint }}
<script type="text/javascript" src="{{ $scripts.Permalink }}" integrity="{{ $scripts.Data.Integrity }}" media="screen"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment