Skip to content

Commit

Permalink
Add default image size for lazy loaded images (#233)
Browse files Browse the repository at this point in the history
* Add default image size for lazy loaded images

* Rewrite code to set image dimensions

Here were the problems, and here’s the solution:

1. I had to mount the static folder to assets/ as suggested by @bep to
be able to get all images as resources
2. You have to be careful about some types, like for example if you call
safeURL on a path the returned object isn’t a string, so you can’t pass
it to .Page.Resources.GetMatch
3. I had to use the .Page object to get resources.
4. Trying to evaluate width and height on an SVG resource fails. We use
some SVGs in Markdown, as we sometimes use the format for lightweight
game sprites and other graphic design.
  • Loading branch information
NathanLovato authored Mar 29, 2021
1 parent 3a8419c commit db870f0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 6 additions & 0 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ target = "assets/js"
source = "assets/scss"
target = "assets/scss"

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

# Shortcuts in the docs section
[[menu.shortcuts]]
name = "<i class='fas fa-level-up-alt'></i>&nbsp;Back to GDQuest.com"
Expand Down Expand Up @@ -102,6 +106,7 @@ privacyEnhanced = true
dir = ":cacheDir/modules"
maxAge = -1


[markup]
defaultMarkdownHandler = "goldmark"

Expand All @@ -110,6 +115,7 @@ defaultMarkdownHandler = "goldmark"
unsafe = true

[module]

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

Expand Down
17 changes: 16 additions & 1 deletion layouts/_default/_markup/render-image.html
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
<img loading="lazy" src="{{ .Destination | safeURL }}" alt="{{ .Text }}" {{ with .Title}} title="{{ . }}"{{ end }} />
{{ $path := .Destination | safeURL }}
{{ $alt := .Text }}
{{ $resource := .Page.Resources.GetMatch .Destination }}

{{ with $resource }}
{{ if and (eq .ResourceType "image") (ne .MediaType.SubType "svg") }}
<img src="{{ .Permalink | safeURL }}"
alt="{{ $alt }}"
{{ with .Title}}title="{{ . }}"{{ end }}
{{ with .Width }}width="{{ . }}"{{ end }}
{{ with .Height }}height="{{ . }}"{{ end }}
/>
{{ else }}
<img src="$path" alt="$alt" />
{{ end }}
{{ end }}

0 comments on commit db870f0

Please sign in to comment.