Hugo-theme-stack/layouts/partials/helper/image.html
Jimmy Cai 3e18e165e0
feat(helper/image): better detection of external image
By using strings.HasPrefix, it matches any images which name starts with http
2020-09-10 23:24:19 +02:00

32 lines
1.3 KiB
HTML

{{ $result := dict "exists" false "local" false "isDefault" false }}
{{ $imageField := .Params.image }}
{{ if $imageField }}
<!-- If page has `image` field set -->
{{ $result = merge $result (dict "exists" true) }}
{{ $url := urls.Parse $imageField }}
{{ if or (eq $url.Scheme "http") (eq $url.Scheme "https") }}
<!-- Is a external image -->
{{ $result = merge $result (dict "src" $imageField) }}
{{ else }}
{{ $pageResourceImage := .Resources.GetMatch (printf "%s" ($imageField | safeURL)) }}
{{ $siteResourceImage := resources.GetMatch (printf "%s" ($imageField | safeURL)) }}
{{ if $pageResourceImage }}
<!-- If image is found under page bundle -->
{{ $result = merge $result (dict "local" true) }}
{{ $result = merge $result (dict "src" $pageResourceImage) }}
{{ else if $siteResourceImage }}
<!-- Try search image under site's assets folder -->
{{ $result = merge $result (dict "local" true) }}
{{ $result = merge $result (dict "src" $siteResourceImage) }}
{{ else }}
<!-- Can not find the image -->
{{ errorf "Failed loading image: %q" $imageField }}
{{ $result = merge $result (dict "exists" false) }}
{{ end }}
{{ end }}
{{ end }}
{{ return $result }}