`.Page.Resources.Get` automatically publishes reasource, `resources.Get` does not

I’m running into an issue where it looks like .Page.Resources.Get causes a resource to automatically get published, even if I never call .Publish, .Permalink, or .RelPermalink. My understanding was that resources were only published once one of those things were called/read. This is supported by the fact that resources.Get doesn’t appear to auto-publish the resource.

However, when I use .Page.Resources.Get then resources.Copy I end up with 2 published copies of the resource.

This is problematic when I get the resource a second time because it auto-publishes the resource into the same location as the previous call.

My use case is creating multiple sizes of the same image. From different pages that don’t need to know about one another, so creating all the sizes in one location isn’t desirable.

How do I prevent this double-publishing?

Here’s an example of an image render hook the causes the issue.

{{ $name := .Destination }}
{{ $resize := index .Attributes "resize" }}
{{ $global := index .Attributes "global" }}
{{ $resource := cond $global (resources.Get $name) (.Page.Resources.Get $name) }}

{{ if $resource }}
	{{ if $resize }}
		{{ $resource = $resource.Resize (printf "%s photo" $resize) }}
		{{ $name = replaceRE `\.([^.]*\z)` (printf "-%s.$1" $resize) $name }}

		{{ $dir := (path.Split .Page.RelPermalink).Dir }}
		{{ $path := printf `%s%s` $dir $name }}
		{{ $resource = resources.Copy $path $resource }}
	{{ end }}
{{ end }}

<img src="{{ $resource.RelPermalink | safeURL }}" />

And a branch with a minimal repro

Excluding those with ResourceType equal to page (i.e., content files), page resources are always published. You can disable that behavior with build options.

1 Like

Ah, that make sense, thanks. That tidbit totally slipped my mind.

Turns out the auto-publishing wasn’t causing the warning, but rather because I was copying resources into the same location when renaming files for cache busting. I can be a little more cautious to avoid that.

I wish fingerprint didn’t rename resources or there was a resource.Rename function. It has led to a couple of issues like this, but at least I’m able to work around it. Thanks again.

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