Pass attributes to image render hook

If your content structure is like this…

content/articles/
└── article-1/
    ├── image.png
    └── index.md

… it is called page bundle, and the image is a page resource.

If your render hook is something like this…

layouts/_default/_markup/render-image.html
{{- $u := urls.Parse .Destination -}}
{{- $alt := plainify .Text -}}
{{- $title := plainify .Title -}}
{{- $img := "" -}}

{{- if $u.IsAbs -}}
  {{- with resources.GetRemote $u.String -}}
    {{- with .Err -}}
      {{- errorf "%s" -}}
    {{- else -}}
      {{- $img = . -}}
    {{- end -}}
  {{- else -}}
    {{- errorf "Unable to get remote image" -}}
  {{- end -}}
{{- else -}}
  {{- with .Page.Resources.GetMatch $u.Path -}}
    {{- $img = . -}}
  {{- else -}}
    {{- errorf "Unable to get local image" -}}
  {{- end -}}
{{- end -}}

{{- with $img -}}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}"
    {{- with $alt }} alt="{{ . }}" {{- end -}}
    {{- with $title }} title="{{ . }}" {{- end -}}
  >
{{- end -}}

It will automatically determine the dimensions of the image whether it is local or remote.

![Alternate text](a.jpg "This is the title")
![Alternate text](https://gohugo.io/images/gohugoio-card-1.png "Hugo rocks!") 

You can modify this render hook to parse the image path for a query string. For example:

![Alt text](a.jpg?w=400&h=300)
![Alt text](https://gohugo.io/images/gohugoio-card-1.png?w=250&h=175)

Then do some conditional checking. If the dimensions are present, scale and crop using the .Fill method.

References:

3 Likes