I’m trying to build a template which gets the first image in the page content to use as a featured image (as suggesed here).
I have the file in the page bundle, manage to find it with regex in the index.html (which supplies the content), match it with a resource and render it.
The thing is, I can not use the specific “image resource” methods such as {{.Width}} on it ( execute of template failed at <.Width>: error calling Width: this method is only available for image resources).
However {{.ResourceType}} and {{.MediaType}} will return image and image/png respectively. Am I doing something wrong or did I encounter a bug?
{{$first_image := ""}}
{{$matches := findRESubmatch `<img\s.*?src=(?:'|")([^'">]+)(?:'|")` .Content 1 }}
{{range $matches}}{{$first_image = index . 1}}{{end}}
{{with .Resources.GetMatch $first_image}}
{{/* These work*/}}
{{.ResourceType}}
{{.MediaType}}
<img src="{{ .Permalink }}" alt="">
{{/* This throws an error */}}
{{.Width}}
{{end}}
I’m currently using hugo v0.111.3+extended linux/amd64 BuildDate=2023-03-16T08:41:31Z VendorInfo=debian:0.111.3-1
Include a link to the source code repository of your project, because we really need the context of seeing your templates and partials to be able to help you. It is trivial to do a quick git clone on your repo, then run hugo server in your project, to help you out. On the other hand, recreating your code from screenshots, or sort of guessing at it, is not.
If you can’t share your repository for whatever reason, consider creating a dummy repo that you can share, which reproduces the problem you’re experiencing.
Having gone through all the material, I’ve found the culprit, which is a specific tiff image (not included in the smaller set I sent prior). I’ve made a workaround in the template logic, to test for the existence of .ResourceType to work around the issue. I share the image & workaround in question here, in case there is a way this is useful to hugo development: found the culprit · d0fd3f018e - lumbung.space - Git with solidaritea
In a more robust approach you would include only those media types that Hugo can process as images. For example:
{{ range .Resources.ByType "image" }}
{{ if in (slice "bmp" "gif" "jpeg" "png" "webp") .MediaType.SubType }}
{{ with .Resize "200x" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}
{{ end }}
{{ end }}
In the above note that files with media type image/tiff are excluded. Although Hugo can process this media type as an image, browsers do not support this image format. So unless you’re going to process to another format (e.g., jpeg or webp), exclude tiff images.