Select first image from page content

Currently I am picking up the cover image from the page/post from front matter. Wonder if there is a way to pick the first figure, image in the content itself?

  {{ if isset .Params "img" }}
        <img src="/images/{{ .Params.img }}" title="{{ .Params.img }} image" />
    {{ end }}
1 Like

Is this issue about rendering a list page, showing an image next to the .Summary?

Just showing an image next to summary

Without doing some regex matching on .RawContent or .Content, you can split the summary manually:

Markdown

Aute pariatur sint sint adipisicing duis laborum aute ipsum excepteur officia. 

![A kitten](a.jpg)

<!--more-->

Laboris excepteur sunt eiusmod duis dolore est dolore consectetur est fugiat id ad.

But if you decide to do this, you will need link and render hooks to properly resolve the destinations when displayed in a different context (i.e., a list instead of a single page).

Let me know if you decide to pursue this; I can provide the hooks.

Thanks, but this seems to be beyond my skill level.

I think I’ll just continue to use image from the front matter using .Params "img" for now.

I’m not able to do what Joe could do but you could do something simpler that might be almost as good.

If you use page bundles go with

  1. specify image with img:
    {{- $src := $.Page.Resources.GetMatch .Params.img }}

  2. fall back to first image in the page bundle in case you forget to set it

{{- range first 1 (.Resources.ByType "image") }}
{{- $src := . }}
{{ end }}
  1. fall back to a default image if there are no images in the page bundle
    {{- $src := resources.Get "/images/fallback.jpg" }}

You’ll probably want to checks if the files exists.

1 Like

I’ve managed to resolve it by checking the content for image links using regex and working with the first one that is returned. Note that your particular regex query depends on what type of content you have. The example below works on HTML image tags.

{{$first_image := ""}}
{{$matches := findRESubmatch `<img\s.*?src=(?:'|")([^'">]+)(?:'|")` .Content 1 }}
{{range $matches}}{{$first_image = index . 1}}{{end}}
  {{with .Resources.GetMatch $first_image}}
    <img src="{{ .Permalink }}" alt="">
    {{end}}

Hope that this can be of help for others!

1 Like