{{ $id := delimit (slice "gallery" (partial "functions/uid.html" .)) "-" -}}
{{ $content := .Inner -}}

{{/* find all img tags */}}
{{ range findRE `<img\s+[^>]*>` $content -}}
  {{ $imgTag := . -}}
  {{/* extract src attribute */}}
  {{ with findRESubmatch `src=['"]([^'"]+)['"]` $imgTag -}}
    {{ $srcAttr := index (index . 0) 0 -}}
    {{ $srcValue := index (index . 0) 1 -}}
    {{ $srcValueFinal := $srcValue -}}

    {{ if or (hasPrefix $srcValue "http://") (hasPrefix $srcValue "https://") -}}
      {{ with resources.GetRemote $srcValue -}}{{ $srcValueFinal = .RelPermalink -}}{{ end -}}
    {{ else -}}
      {{ with $.Page.Resources.GetMatch $srcValue -}}
        {{ $srcValueFinal = .RelPermalink -}}
      {{ else -}}
        {{ with resources.GetMatch $srcValue -}}{{ $srcValueFinal = .RelPermalink -}}{{ end -}}
      {{ end -}}
    {{ end -}}

    {{ $newTag := replace $imgTag $srcAttr (printf `src="%s"` $srcValueFinal) -}}
    {{ $content = replace $content $imgTag $newTag -}}
  {{ end -}}
{{ end -}}


<div id="{{- $id -}}" class="gallery">
  {{ $content | safeHTML -}}
</div>
