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 Feb 17, 2021
1 parent d14362c commit 720eb70
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 @@ -93,6 +93,7 @@ privacyEnhanced = true
dir = ":cacheDir/modules"
maxAge = -1


[markup]
defaultMarkdownHandler = "goldmark"

Expand All @@ -101,9 +102,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 720eb70

Please sign in to comment.