May 12, 2017

How to Display a Featured Photo on a Hugo-Powered Photo Blog's Front Page

I use the static website generator Hugo for this homepage. However I find that Hugo's capabilities are somehow restrained if you post a lot of photographs like I do.

So far my approach has been to automatically generate markdown that includes the photos I want to show in a post chronologically. Furthermore I enforce that only the first photo is shown on the homepage with the `

` switch. So my typical post looks like this:

+++
title = "Title"
date = "date"
tags = [ "tag1", "tag2" ]
topics = [ "topic1" ]
type = "post"
+++

Intro Text

![description](link_to_pic_1)
<!--more-->
[Picture location](link)

![description](link_to_pic_2)
[Picture location](link)

![description](link_to_pic_3)
[Picture location](link)
...

One thing that I disliked in particular was that either the chronologically first picture gets shown on the summary page (which is not necessarily the nicest one) or I am forced to put the nicest one on top (which would break the chronological order).

I asked for advice in the Hugo support forum and one nice member outlined a way how to implement what I need. The key idea is to use the front matter of the post (the meta data of the post defined between ++++++) to add a new variable that holds the link to the selected photo that needs be shown on the summary page (and maybe a second variable that holds some text):

+++
title = "Title"
date = "date"
tags = [ "tag1", "tag2" ]
topics = [ "topic1" ]
type = "post"
featured_image = "link_to_pic_3"
featured_text = "Hey I get displayed beneath the featured picture!"
+++

As I never looked into the internals of Hugo and how Hugo Templates work, I needed to dig around a bit. I am also not completely sure if this is special for the Blackburn Template I use or directly applicable to any other template you might use. However, maybe it is useful for somebody else!

When you use the Blackburn template, the way how Hugo renders the post summary page is defined by the file [base_path_of_your_hugo_project]/themes/blackburn/layouts/_default/summary.html. I modified the file as follows:

<article>
  <header>
    <h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
    {{ partial "post_meta.html" . }}
  </header>

  {{ if isset .Params "featured_image" }} <!--do we have a featured pic?-->
    <p>
      <img src="{{ .Params.featured_image }}"> <!--yes: include that pic-->
    </p>
    {{ if isset .Params "featured_text" }}
      <p>
        {{ .Params.featured_text }}
      </p>
    {{ end }}
  {{ else }}
  <p>
    {{ .Summary }} <!--no: just show the ordinary summary-->
  </p>
  {{ end }}

  {{ if .Truncated }}
  <footer>
    <a href="{{ .RelPermalink }}">Read more<i class="fa fa-angle-double-right fa-fw"></i></a>
  </footer>
  {{ end }}
</article>

Easy as pie!

Update: In the meantime I have forked Blackburn. You can get my modified version from Github.

© holger 2015 - 2020 |