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 }}

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:


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

![A kitten](a.jpg)


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