How to publish unmodified image with hash in filename

Hello all,

I need a hashed filename for unmodified asset images like the ones modified get (xxhash). An example with the main question in the else branch.

{{- with resources.GetMatch (printf "portraits/%s.jpg" .) -}}
	{{- $image := . -}}
	{{- if gt $image.Height 40 }}
		{{- $image = $image.Fit "40x40" -}}
	{{- else -}}
		<!-- What should go here to get a hashed filename for the unmodified image? -->
	{{- end -}}
	<img src="{{ $image.RelPermalink }}">
{{- end -}}

So if the image is greater that 40px it gets a filename in the public folder with an xxhash in the name. But if it’s 40 or smaller the filename will be the same as in the assets folder. I need both with a hash in the name.

Thanks in advance!

The following does the job in the else branch, but I don’t think this is a good solution as I don’t know what that does with the image and definitely changes the file:

{{- $image = $image.Process "" -}}
{{ with $i := resources.Get "a.jpg" }}
  {{ if gt .Height 40 }}
    {{ $i = .Fit "40x40" -}}
  {{ else }}
    {{ $newFileName := printf "%s.%s" (hash.XxHash .Name) (.MediaType.FirstSuffix.Suffix)  }}
    {{ $i = resources.Copy $newFileName . }}
  {{ end }}
  <img src="{{ $i.RelPermalink }}">
{{ end }}

https://gohugo.io/functions/resources/copy/

Upon reflection, it would be better to hash the content.

{{ with $i := resources.Get "a.jpg" }}
  {{ if gt .Height 500 }}
    {{ $i = .Fit "40x40" -}}
  {{ else }}
    {{ $newFileName := printf "%s.%s" (hash.XxHash .Content) (.MediaType.FirstSuffix.Suffix)  }}
    {{ $i = resources.Copy $newFileName . }}
  {{ end }}
  <img src="{{ $i.RelPermalink }}">
{{ end }}

Thank you! It is quite close. But the built in “renamer” puts the file into the correct subfolder within public and adds language code to to the original filename. So it generates [filename]_[lang]_[hash].[extension]

I understand now that it can be programmed into this example. But isn’t there some config variable or method to use this filename creation template to all files copied/created into the public folder from assets?

No, there is not.

1 Like

The “hu” stands for “Hugo” not " Hungarian"… language isn’t part of the equation here. Just a coincidence.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.