.Resize with vars

Can’t seem to find a solution anywhere, and my syntax knowledge is still growing…

I’d like to process an image. I have some .png that are transparent, and Hugo doesn’t want to give it a background as it preserves that. So, I thought I’d change the image to a jpg which doesn’t have an alpha channel. However, I’m not sure how to change just the bgcolor or the format. Seems as if the image processor wants to do that secondarily to another function, like .Resize
I’m ok with that, but I don’t want to change the dimensions of the image. I can’t figure out how to combine a var with string that .Resize is looking for.

# shortcodes/img.html

{{ $src := .Page.Resources.GetMatch (printf "*%s*" (.Get "src")
# will resize to 600px wide, convert to jpg with a white background
{{$src.Resize  "600w jpg #ffffff" }} 
# would like to keep image size the same
{{ $srcOrigW := $src.Width }} # this does give the width
{{ $src.Resize "$srcOrigW jpg #ffffff" }} # throws error
## <$src.Resize>: error calling Resize: must provide Width or Height

I also tried: {{ $src.Resize (printf "%s%s" $srcOrigW " jpg #fff") }} to no avail. Tried various combos of that as well.

1 Like

Your printf syntax (the one share here) is flawed. First arg is a string, second and subsequent are the variables which will be “concatenated” into to the string. This is the correct syntax for your printf :

 {{ $src.Resize (printf "%sx jpg #fff"  $srcOrigW) }}

If it’s not working it might be that $src.Width is not a string but an int if so try:

 {{ $src.Resize (printf "%sx jpg #fff"  (string $srcOrigW)) }}

Or use a different verb as %s is for string only.


Thank you for the speedy response.
I did need to convert the .Width to a string

1 Like