Skip to content

Instantly share code, notes, and snippets.

@jakejarvis
Created October 30, 2019 01:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakejarvis/71c0d6de7462420572397640913fc846 to your computer and use it in GitHub Desktop.
Save jakejarvis/71c0d6de7462420572397640913fc846 to your computer and use it in GitHub Desktop.
Hugo shortcode for resizing retina images with max-width
<!-- Automatic resizing for HiDPI/retina images -->
<!-- https://gohugo.io/content-management/image-processing/ -->
{{- $original := .Page.Resources.GetMatch (.Get "src") -}}
{{- .Scratch.Set "image" $original -}}
{{- $maxWidth := 910 -}}
{{- if .Get "width" }}
{{- $inputWidth := (int (.Get "width")) -}}
{{- $retinaWidth := (mul $inputWidth 2) -}}
{{- if gt $original.Width $retinaWidth -}}
{{- $finalWidth := (printf "%dx" $retinaWidth) -}}
{{- .Scratch.Set "image" ($original.Resize $finalWidth) -}}
{{- end -}}
{{- else -}}
{{- $inputWidth := $maxWidth -}}
{{- if gt $original.Width 1820 -}}
{{- .Scratch.Set "image" ($original.Resize "1820x") -}}
{{- end -}}
{{- end -}}
{{- $image := .Scratch.Get "image" -}}
{{- if .Get "caption" -}}
<figure>
<picture>
{{- else -}}
<p>
{{- end -}}
<img src="{{ $image.Permalink }}"{{ if .Get "alt" }} alt="{{ .Get "alt" }}"{{ end }}{{ if .Get "width" }} width="{{ .Get "width" }}"{{ end }}{{ if .Get "caption" }} title="{{ .Get "caption"}}"{{ end }}>
{{- if .Get "caption" -}}
</picture>
<figcaption>{{ .Get "caption" }}</figcaption>
</figure>
{{- else -}}
</p>
{{- end -}}

{{< image src="images/example.png" width="750" alt="Mouseover text" caption="Optional caption text below image" >}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment