Hello. How to use list of img with srcset?
+++
mainImg = "https://imgopt.pages.dev/warns_bitcoin_community.png_1024.jpg"
mainImgs = ['https://imgopt.pages.dev/warns_bitcoin_community.png_1024.jpg', 'https://imgopt.pages.dev/warns_bitcoin_community.png_768.jpg', 'https://imgopt.pages.dev/warns_bitcoin_community.png_500.jpg']
+++
And I need to add this images to img srcset
{{ with .Params.mainImg }} <- need to change to mainImgs
{{ with resources.GetRemote . }}
<img
class="object-cover"
src="{{ .Permalink }}"
alt="{{ .Params.altMainImg }}"
title="{{ .Params.titleMainImg }}"
loading="lazy"
decoding="async"
crossorigin="anonymous"
sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
srcset="small.jpg 500w, medium.jpg 768w, {{ .RelPermalink }} 1024w"
/>
{{ end }}
{{ end }}
src=“{{ .Permalink }}” ← 1024.jpg
srcset=“500.jpg 500w, 768.jpg 768w, 1024.jpg 1024w”
How to do this logic?
Looks like you are looking for the range
function
I know range. I need to range to variable and insert from variable? Because I don’t know how to range this in img param
mmh, guess I did not get the point. how does the final result look like
one img tag for each element mainImgs?
content of srcset?
I need to fill all srcset with range
srcset=“small.jpg 500w, medium.jpg 768w, {{ .RelPermalink }} 1024w”
with
srcset=“500.jpg 500w, 768.jpg 768w, 1024.jpg 1024w”
for your case if the sizes are fixed and the image names match maybe something like that
guess this should help for a go
{{ $mainImg := "img_1024.jpg" }}
{{ $sizes := slice "500" "750" }}
{{ $srcset := slice (printf "%s 1024w" $mainImg) }}
{{ range $sizes }}
{{ $srcset = append (printf "%s %sw" (replace $mainImg "1024" .) .) $srcset }}
{{ end }}
<img class="image" srcset="{{ delimit $srcset ", " }}" />
output:
<img class="image" srcset="img_1024.jpg 1024w, img_500.jpg 500w, img_750.jpg 750w" />
1 Like
To get all images published locally you will need to call permalink for all images
+++
[params]
mainImgs = ["images/bare-metal-website_1024.png", "images/bare-metal-website_500.png", "images/bare-metal-website_750.png"]
+++
taking the first as default
picking up the size from the end
render all images locally
{{ with .Params.MainImgs }}
{{ with resources.Get (index . 0) }}
{{ $srcset := slice }}
{{ range $.Params.MainImgs }}
{{ with resources.Get . }}
{{ $size := index (index (findRESubmatch `.*_(\d+)\.png$` .) 0) 1 }}
{{ $srcset = append (printf "%s %sw" .RelPermalink $size) $srcset }}
{{ end }}
{{ end }}
<img src="{{ .RelPermalink }}" class="image" srcset="{{ delimit $srcset ", " }}" />
{{ end }}
{{ end }}
use GetRemote if you download the images
you might also consider using hugo image pipline
and just download one and resize yourself
1 Like
system
Closed
May 26, 2024, 8:15am
8
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.