Last Modified: Wednesday, Feb 13, 2019
https://regisphilibert.com/blog/2018/01/hugo-page-resources-and-how-to-use-them/
Create a headless media folder
hugo new media/index.md
media/index.md title: “Media” date: … draft: false headless: true
Keep your images in this folder.
Create a Page var in your template to reference the headless media folder (/site/content/media)
{{ $media := (.Site.GetPage "/media")}}
Now you have a couple options available.
Range through all images
{{ $images := $media.Resources.ByType "image"}} {{ range $images}} <img src="{{.RelPermalink}}" alt="hi"> {{end}}
Display a specific image (in a template)
{{ $media := (.Site.GetPage "/media")}} {{ $src := replace .Params.img.src "/media/" "" }} (Remove /media/ for netlifyCMS filepath issue) {{ $image := ($media.Resources.GetMatch $src)}} {{ $alt := .Title }} {{ $title := .Params.img.title}} <img src="{{$image.RelPermalink }}" alt="{{ $alt }}"{{ with $title }} title="{{.}}"{{end}}>
In the front matter of the page you’re on, you’ll have something like:
img:
src: hi.jpg
alt: hi
- 3. Display a specific image (in markdown)
Resize Images
{{ $media := (.Site.GetPage "/media")}} {{ $src := replace .Params.image.src "/media/" "" }} {{ $image := ($media.Resources.Match $src)}} {{ $alt := .Title }} {{ $title := .Params.img.title}} {{ range $image}} <img src="{{(.Resize "712x").RelPermalink }}" alt="{{ $alt }}"{{ with $title }} title="{{.}}"{{end}}> {{ end}}
Resize & create
srcset
{{ $media := (.Site.GetPage "/media")}} {{ $src := replace .Params.image.src "/media/" "" }} {{ $image := ($media.Resources.Match $src)}} {{ $caption := .Params.img.caption}} {{ $alt := .Title }} {{ $title := .Params.img.title}} {{ $sizes := $.Site.Params.sizes_blog }} {{ range $image}} <figure> <img src="{{.RelPermalink }}" alt="{{ $alt }}" srcset="{{(.Resize "549x").RelPermalink }} 549w, {{(.Resize "1098x").RelPermalink }} 1098w, {{(.Resize "712x").RelPermalink }} 712w, {{(.Resize "1424x").RelPermalink }} 1424w" sizes="{{ $sizes}}" class=""{{ with $title }} title="{{.}}"{{end}}> {{ with $caption }} <figcaption class=""> {{ . | markdownify }} </figcaption> {{end }} </figure> {{ end}}