Displaying Featured Images

Hi Hugo community.

First of all - much gratitude for such a great site builder and support community. Impressive!

I’m having trouble displaying Featured images in single pages, and lists.

I’ve scanned the knowledge base (including Post featured image) and still can’t fix my issue.

I have a section called articles in my /content DIR.

├── content
│   ├── articles
│   │   ├── _index.md
│   │   ├── our-story
│   │   │   ├── images
│   │   │   │   └── image1.jpg
│   │   │   │   └── image2.jpg
│   │   │   └── index.md

Each article contains an /images DIR per the new Page Bundle approach.

I then set a featured image in the index.md of the article:

---
title: "Our Story"
date: 2018-02-10T11:26:27+11:00
featured_image: "image1.jpg"
featured_image_caption: "Caption Blah Blah"
---

I have a partial that is capable of accessing the featured_image_caption variable with:

{{ with .Params.featured_image_caption }}
  <p class="featured-img-caption">{{ . }}</p>
{{ end }}

But how do I access that featured image?

The only way I can display it at the moment is with:

{{ with .Resources.ByType "image" }}
  {{ range . }}
      <img src="{{ .RelPermalink }}" alt="{{ $.Title }}">
  {{ end }}
{{ end }}

But that (predictably) shows all images in the Article’s /images DIR.

FYI - I’m using that same partial in the single.html and list.html here:

└── themes
    └── mytheme
        ├── layouts
        │   ├── articles
        │   │   ├── list.html
        │   │   └── single.html

How can I filter the result to provide only the image declared in the featured_image frontmatter field?

Many thanks for any assistance y’all can provide.

R*

2 Likes

have you try {{ .Params.featured_image }}?

The documentation about this may be a little mix and match.

But what I would recommend is to use the new resources and image processing capabilities in the latest Hugo.

You may get some inspiration from the new showcase section in the docs:

But you would also need to read up on resources vs metadata configuration.

1 Like

I tried that but to no avail. @bep gave me the lead I needed below.

Thanks very much for the lead.

I managed to solve my issue with:

{{ $img := (.Resources.ByType "image").GetMatch "images/*featured*" }}
{{ with $img }}
    <img src="{{ .Permalink }}" alt="{{ $.Title }}">
{{ end }}

The documentation in the showcase template was also handy (regarding the need to include “featured” at the beginning of the filename), as was this page which is an excellent resource for a Go/Hugo beginner like myself.

I’ll jettison the featured_image: frontmatter field now.

Much appreciated!
R*

4 Likes