Differentiate img loading eager lazy

I want to be most of my images lazy loading, but some of them should be eager (above the line - core web vitals).

I can not pass loading variable.

single.html template

{{ partial "imgoptim.html" (dict "ctx" . "loading" "eager") }}

partial template

{{- $src := .Page.Resources.GetMatch .Params.image }}

{{- $alt := .Params.title }}

{{- $loading := .loading }}

{{- with $src }}

<img srcset='

{{- if ge .Width "480" -}}

  {{ (.Resize "480x").RelPermalink }} 480w,

{{- end }}

{{- if ge .Width "800" -}}

  {{ (.Resize "800x").RelPermalink }} 800w,

{{- end }}

{{- if ge .Width "1200" -}}

  {{ (.Resize "1200x").RelPermalink }} 1200w{{- end }}' sizes="(max-width:600px) 480px, (max-width:1024px) 800px, 1200px" src="{{ .RelPermalink }}" decoding="async" {{ if eq $loading eager }}loading="eager"{{ else }}loading="lazy"{{ end }} alt="{{ $alt }}">

{{- end }}

most pages has default partial (which works btw)

{{ partial "imgoptim.html" . }}

Not tested but I think it should be {{ if eq $loading "eager" }} since it is a string.

can’t evaluate field loading

If that’s the complete partial from the beginning, Same issue as lately

You have a context problem!

  • you pass a dict with two keys

  • you try to work with the DOT-context and access fields not existing

This should work
{{- $loading := .loading }}
{{ with .ctx }}
    {{- $src := .Page.Resources.GetMatch .Params.image }}  
    {{- $alt := .Params.title }}
    {{ with $src}
    .... YOUR CODE HERE ...
    {{ end }}
{{ end }}
1 Like

That error message seems to not match the code line:

you forgot the doule quotes around eager and it should throw:

Error: error building site: template: imgoptim.html:15: function “eager” not defined

for me the code from @frjo should work