Home → Bikeshed → Components
render-image.html
Published:
This render hook builds off of Hugo’s built in one which allows for robust linking to page and site resources with a couple of changes:
- Added width and height attributes to the images (this is overridden by any dimensions specified in
.Attributes
). Attributes can also be defined with a JSON object in the markdown title and if it is it will have presidence over.Attributes
. - Added warnings when a referenced image isn’t found in the site’s assets folder.
Source Code
{{- $u := urls.Parse .Destination -}}
{{- $src := $u.String -}}
{{- $dims := dict -}}
{{- if not $u.IsAbs -}}
{{- $path := strings.TrimPrefix "./" $u.Path }}
{{- $path := strings.TrimPrefix "/assets" $u.Path }}
{{- with or (.PageInner.Resources.Get $path) (resources.Get $path) -}}
{{- $src = .RelPermalink -}}
{{- with $u.RawQuery -}}
{{- $src = printf "%s?%s" $src . -}}
{{- end -}}
{{- with $u.Fragment -}}
{{- $src = printf "%s#%s" $src . -}}
{{- end -}}
{{- $dims = merge $dims (dict "width" (string .Width) "height" (string .Height)) -}}
{{- else -}}
{{- warnf "Image %s referenced in %s not found." $.Destination $.PageInner.File.Filename -}}
{{- end -}}
{{- end -}}
{{- $attributes := merge (dict "alt" .Text "src" $src) $dims .Attributes -}}
{{- with .Title -}}
{{- if hasPrefix . `{` -}}
{{- $attrObj := transform.Unmarshal . -}}
{{- range $k, $v := $attrObj -}}
{{- $attributes = merge $attributes (dict $k $v) -}}
{{- end -}}
{{- else -}}
{{- $attributes = merge $attributes (dict "title" . ) -}}
{{- end -}}
{{- end -}}
<img
{{- range $k, $v := $attributes -}}
{{- if $v -}}
{{- printf " %s=%q" $k $v | safeHTMLAttr -}}
{{- end -}}
{{- end -}}>
{{- /**/ -}}