HomeBikeshedComponents

render-image Render Hook

Published:

This render hook improves how images are handled by Hugo. So far it,

  • ✅links images robustly through Hugo’s asset and resources pipeline, and
  • ✅adds the width and height attribute to prevent layout shift.

Soon I plan to,

  • support custom attributes, and
  • discover alternative media formats and includes them with the <picture>/<source> elements.

I don’t plan to support Hugo’s native image processing, but I do plan to add shortcodes to help with handling the <picture>/<source> (for art direction instead of just alternative image formats) as well as a pipeline to process images in GitHub actions.

Source Code

{{- $attrs := dict
    "src" .Destination
    "alt" .Text
    "title" .Title

-}}
{{- with or (.Page.Resources.GetMatch .Destination) (resources.Get .Destination) -}}
    {{- $attrs = merge $attrs (dict
        "src" .Permalink
        "width" .Width
        "height" .Height
    ) -}}
{{- end -}}
<img{{ range $k, $v := $attrs }} {{ print $k `="` $v `"` | safeHTMLAttr }}{{ end }}>