{{/* Get album folder or default to `gallery/`. */}}
{{ $album := "" }}
{{ with .Get "album" }}{{ $album = . }}{{else}}{{ $album = "gallery" }}{{end}}

{{/* Set image path and page bundle that images are associated with. */}}
{{ $album_path := "" }}
{{ $resource_page := "" }}
{{ if eq .Page.Parent.Type "widget_page" }}
  {{ $album_path = printf "%s/%s/*" (path.Base (path.Split .Page.Path).Dir) $album }}
  {{ $resource_page = $.Page.Parent }}
{{ else }}
  {{ $album_path = printf "%s/*" $album }}
  {{ $resource_page = $.Page }}
{{ end }}

<div class="gallery">

  {{/* Attempt to automatically load gallery images from page bundle */}}
  {{ $images := ($resource_page.Resources.ByType "image").Match $album_path }}
  {{ with $images }}
  {{ range $images }}
    {{ $image := .Resize "x190" }}
    {{/* Check if the user set a caption for this image */}}
    {{ $filename := .Name }}
    {{ $caption := "" }}
    {{ if $.Page.Params.gallery_item }}
    {{ range (where $.Page.Params.gallery_item "album" $album) }}
      {{if eq (printf "%s/%s" $album .image) $filename}}{{ with .caption }}{{ $caption = . }}{{end}}{{end}}
    {{ end }}
    {{ end }}
  <a data-fancybox="gallery-{{$album}}" href="{{ .RelPermalink }}" {{ with $caption }}data-caption="{{.}}"{{ end }}>
  <img src="{{ $image.RelPermalink }}" alt="">
  </a>
  {{end}}

  {{else}}
  {{/* Load gallery images from the `static/img/` media library or internet */}}

  {{ if $.Page.Params.gallery_item }}
  {{ range (where $.Page.Params.gallery_item "album" $album) }}
  {{/* Set image path. */}}
  {{ $.Scratch.Set "src" .image }}
  {{ if gt (len .image) 4 }}
    {{ if ne "http" (slicestr .image 0 4) }}
      {{ $.Scratch.Set "src" (printf "img/%s" .image | relURL) }}
    {{ end }}
  {{ end }}
  <a data-fancybox="gallery{{ with .album }}-{{.}}{{ end }}" {{ with .caption }}data-caption="{{.}}"{{ end }} href="{{$.Scratch.Get "src"}}">
    <img src="{{$.Scratch.Get "src"}}" alt="">
  </a>
  {{end}}
  {{else}}
    {{ errorf "Unable to load gallery in %s." .Page.Filename }}
  {{end}}
  {{end}}
</div>