How to use an object in range?

After I speed tested my shiny created website with Google pagespeed, I was quickly reminded how much more optimisation I had to do.

The most benefit is taken from using the picture tag with a fallback for older browsers.

<picture>
    <source srcset="{{ .imageWebp2 | absURL }} 2x, {{ .imageWebp | absURL }} 1x" type="image/webp">
    <source srcset="{{ .image2 | absURL }} 2x, {{ .image | absURL }} 1x" type="image/jpeg">
    <img class="img-fluid" src="{{ .image | absURL }}" alt="">
 </picture>

This works great for single items. But when it comes to range, I’m lost. I have no idea how to solve it.

For example in Vex products as shown here:

we have an images array:

images: 
  - "images/showcase/showcase-1.png"
  - "images/showcase/showcase-2.png"
  - "images/showcase/showcase-3.png"
  - "images/showcase/showcase-4.png"

And in partials/product.html we have this loop:

<div class="product-slider">
    {{ range (where .Site.RegularPages "Section" "products") }}
       <div class="block">
            <img class="img-fluid" src="{{range first 1 .Params.images}}{{.|absURL}}{{end}}" alt="{{.Title}}">
         </div>
    {{ end }}
   </div>
</div>

Is there a way to use an object inside the images:

images: 
  -  normal: "images/showcase/showcase-1.png"
     webp: "images/showcase/showcase-1.webp"
  -  normal: "images/showcase/showcase-2.png"
     webp: "images/showcase/showcase-2.webp"

That way I could access it like
{{.normal | absURL}} and {{.webp | absURL}}

Is that possible?
Many Thanks

{{ range $key, $value := first 1 .Params.images }}
  {{$key}}: {{ $value }}
  {{ if eq $key "webp"}}
    It's the webp value: {{$value}}
  {{ else if eq $key "normal" }}
    normal value: {{$value}}
  {{ end }}
{{ end }}

not tested, but something like that. The $key, $value := whatisranged is used to access keys and values separately.

Hi David,

Thank you. You’ve inspired me to an easier solution.

It would be easier to use a path without file extension and then use string concatenation.

{{ $title := .Title }}
{{ range $path := first 1 .Params.images }}
    {{$path := $path|absURL }}
    <picture>
        <source srcset="{{print $path "@2x.webp"}} 2x, {{print $path ".webp"}} 1x" type="image/webp">
        <source srcset="{{print $path "@2x.png"}} 2x, {{print $path ".png"}} 1x" type="image/png">
        <img class="img-fluid" src="{{print $path ".png"}}" alt="{{$title}}">
    </picture>
{{ end }}

And the product will have this:

images: 
  - "images/showcase/showcase-1"

It works!

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