HUGO

Showing featured image only if there in Cactus theme

Hello guys,

I’m trying to figure out how to add featured images to my post list on the front page. So far, I have found a way to show a featured image by adding this line to my post-list.html:

<a href='{{ .Permalink }}'><img{{ with .Params.featured_image }} src="{{ . }}"{{ end }} alt="{{ .Title }}"></a>

I also moved the description below the image (just because I like it). At the moment, my post-list.html looks like this:

<ul id="post-list">
    {{ range where .Paginator.Pages "Section" "ne" "" }}
        <li>
            <a href='{{ .Permalink }}'><aside class="dates">{{ .Date.Format "Jan 2 2006" }}</aside></a>
            <a href='{{ .Permalink }}'>{{ .LinkTitle }}</a>
            <a href='{{ .Permalink }}'><img{{ with .Params.featured_image }} src="{{ . }}"{{ end }} alt="{{ .Title }}"></a>
            <h2>{{ .Description | markdownify }}</h2>
        </li>
    {{ end }}
</ul>

Now, I would like the featured image to show if there is the featured_image params in my post, but NOT if there’s no such value in the post. Is there a way to achieve this?

So far, if there’s no image set inside the post, the post list shows the title twice trying to also show an image with link, see screenshot below (the problem makes sense to me looking at the code above).

How can I get the right query done?

Greatly appreciate any ideas :slight_smile:

I actually found out myself how to do it (after a few hours of searching and playing around).

Hopefully, this topic will help others.

Solution:

<ul id="post-list">
    {{ range where .Paginator.Pages "Section" "ne" "" }}
        <li>
            <a href='{{ .Permalink }}'><aside class="dates">{{ .Date.Format "Jan 2 2006" }}</aside></a>
            <a href='{{ .Permalink }}'>{{ .LinkTitle }}</a>
{{ if .Params.featured_image }}
            <a href='{{ .Permalink }}'><img{{ with .Params.featured_image }} src="{{ . }}"{{ end }} alt="{{ .Title }}"></a>
{{ end }}
            <h2>{{ .Description | markdownify }}</h2>
        </li>
    {{ end }}
</ul>