Generating a picture tag from page variables

I’d like to have a variable in my front matter of each post for an image, something like this:

myvariable: this-is-my-image-slug

Then in my template, I’d like the output to be like this:

<picture>
<source srcset="/blog/post-slug/img/this-is-my-image-slug.webp" type="image/webp">
<source srcset="/blog/post-slug/img/this-is-my-image-slug.png" type="image/png"> 
 <img src="/blog/post-slug/img/this-is-my-image-slug.png">
</picture>

I’m having difficulty with making this code work in the srcset and src parameters above:

{{ .RelPermalink }}{{ .Params.myvariable }}.webp

It doesn’t like the .webp extension being added.

Is there a way to concatenate .Params.myvariable and .webp as input to .RelPermalink

Thanks!

Mario

1 Like

Try something like

  {{- $foo := print .RelPermalink .Params.myvariable ".webp" -}}

or

  {{- $foo := printf "%v%v%v" .RelPermalink .Params.myvariable ".webp" -}}
  {{- $foo -}}

Best to use an image render hook.

1 Like