Cannot copy image resource without changes

I have a photo/image for the post in $resource variable. In my use case it’s located in filesystem with some timestamp-like name and I’d like to rename it during Hugo processing. My wish is to have this working: {{< img "2024-12-31_09.13.00.jpg" "human-readable-name.jpg" >}}.

I have some shortcode which, among other stuff, does something like this:

		{{ $thumbname2 := printf "%s/%s%s" (path.Dir $resource.RelPermalink) "thumb_123" (path.Ext $resource.RelPermalink) }}
		{{ $zz := $resource | resources.Copy $thumbname2 }}
		<br>{{$zz.Permalink}} - <img src="{{ $zz.Permalink }}" alt="{{ $zz.Permalink }}" /> 

My expectation is that new file containing thumb_123 should appear on the filesystem and should be accessible (like, the img tag should show it).

However, it does not work! It only works if I explicitly modify the image like this (note Resize on the second line)

		{{ $thumbname2 := printf "%s/%s%s" (path.Dir $resource.RelPermalink) "thumb_123" (path.Ext $resource.RelPermalink) }}
		{{ $zz := $resource.Resize "300x" | resources.Copy $thumbname2 }}
		<br>{{$zz.Permalink}} - <img src="{{ $zz.Permalink }}" alt="{{ $zz.Permalink }}" /> 

Is this expected behavior? Am I doing something wrong? How can I rename existing resource without modifying it?

you omitted how you get your $resource variable populated. You need a resource that can be copied.

but this one works:

  • create an image file as /assets/old-name.png

  • create a page that uses the shortcode

    ---
    title: Example
    ---
    
     # an image
    
     {{< image "old-name.png" >}}
    
  • the shortcode in /layouts/shortcodes/image.html

    {{ $name := .Get 0 }}
    {{ with resources.Get $name }}
       {{ $zz := . | resources.Copy "img/new-name.png" }}
       <br />{{ $zz.Permalink }} - <img src="{{ $zz.Permalink }}" alt="{{ $zz.Permalink }}" />
    {{ end }}
    
  • image will be copied to /public/img/new-name.png
    see resources.Copy | Hugo

If you are working with page resources:
https://github.com/gohugoio/hugo/issues/10584

2 Likes

Of course it can, just a regular image somewhere in the post like {{ $resource = $.Page.Resources.GetMatch $filename }}

I’m working with images, but thanks, actually your link shares a good workaround - if I add Publish, then it all works fine! I’ll go with this for now…

An image within a page bundle is a page resource.

1 Like

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