Skip to content

Commit

Permalink
Add default image size for lazy loaded images
Browse files Browse the repository at this point in the history
  • Loading branch information
NathanLovato committed Mar 28, 2021
1 parent 3a8419c commit 20ccb2e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
10 changes: 10 additions & 0 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ privacyEnhanced = true
dir = ":cacheDir/modules"
maxAge = -1


[markup]
defaultMarkdownHandler = "goldmark"

Expand All @@ -110,9 +111,18 @@ defaultMarkdownHandler = "goldmark"
unsafe = true

[module]

[[module.imports]]
path = "github.com/gohugoio/hugo-mod-jslibs/instantpage"

[[module.mounts]]
source = "assets/scss"
target = "assets/scss"

[[module.mounts]]
source = "static/img"
target = "assets/img"

[languages]
[languages.en]
languageName = "English"
Expand Down
52 changes: 51 additions & 1 deletion layouts/_default/_markup/render-image.html
Original file line number Diff line number Diff line change
@@ -1 +1,51 @@
<img loading="lazy" src="{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title}} title="{{ . }}"{{ end }} />
<!-- layouts/partials/render-image.html -->
{{ $src := ( .Destination | safeURL ) }}
{{ $fragments := ( split $src "#" ) }}
{{ $src = index ($fragments ) 0 }}
{{ $src = path.Base $src }}
{{ $resource := ($.Page.Resources.ByType "image").GetMatch ( printf "**%s" $src ) }}

{{ with $resource }}
{{ if (eq .MediaType.SubType "svg") }}
{{ warnf "%q" .Permalink }}
{{ else }}
{{ .ResourceType }} || {{ .MediaType.SubType}} || {{.Width}}
{{ end }}
{{ end }}

{{ with $resource }}
{{ warnf "%q %s" . .ResourceType }}
{{ if eq .ResourceType "image" }}
{{ $width := 0 }}
{{ $height := 0 }}
{{ if isset . "Width" }}
{{ $width = .Width }}
{{ $height = .Height }}
{{ end }}
<!-- resize if wider than 800px -->
{{ $resized := cond (lt .Width "800") . ( .Resize "800x" ) }}
<!-- generate a low resolution placeholder to use as background if a JPG -->
{{ $placeholder := "" }}
{{ if eq .MediaType.SubType "jpeg" }}
{{ $placeholder = .Resize "16x q20 jpg Gaussian" }}
{{ end }}
<img src="{{ $resized.RelPermalink }}"

width="{{ $resized.Width }}"
height="{{ $resized.Height }}"
{{ with $placeholder }}style="
background-image: url('data:image/jpg;base64,{{ .Content | base64Encode }}');
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;"{{ end }}
alt="{{ $.Text }}" {{ with $.Title }} title="{{ . }}" {{ end }}
{{ with index ($fragments ) 1 }}class="{{ . }}"{{ end }}
loading="lazy"
>
{{ end }}
{{ else }}
<img src="{{ .Destination | safeURL }}"
alt="{{ .Text }}" {{ with .Title }} title="{{ . }}" {{ end }}
loading="lazy"
>
{{ end }}

0 comments on commit 20ccb2e

Please sign in to comment.