Adding Tag Links to My Hugo Site Posts

September - 2020

NOTE: TODO: This page needs updates to work with MDX

Goal: Get tags working on this site √

This was easy... Tags work out of the box with Hugo. The only thing I did was updated the config file to remove the auto generated categories. That was done by just adding this to the config.toml file:

[taxonomies]
  tag = "tags"

That overwrites the existing [taxonomies] which has categories with this option that only contains tags.

Goal: Put links to the tag pages on the individual post pages √

This was pretty straight forward with a pull from the documentation. The page where the edit was made for my theme is:

hugo-site/themes/MY_THEME/layouts/partials/single/title.html

All I had to do was drop this code in:

{{ range $elem_index, $elem_val := (.GetTerms "tags") }}
    {{- if gt $elem_index 0 }}, {{ end -}}
    <a href="{{ .Permalink }}">{{ .LinkTitle }}</a>
{{- end -}}

That code loops through all the tags. If there is more than one, it puts a comma between them.

Goal: Put links to the tag pages under the post titles on the index pages √

This was pretty much the same as the single page. The pages to edit was:

hugo-site/themes/MY_THEME/layouts/_default/summary.html

This time the code was:

{{ range $elem_index, $elem_val := (.GetTerms "tags") }}
    {{- if eq $elem_index 0 }} - {{ end -}}
    {{- if gt $elem_index 0 }}, {{ end -}}
    <a href="{{ .Permalink }}">{{ .LinkTitle }}</a>
{{- end -}}

The difference is the line {{- if eq $elem_index 0 }} - {{ end -}}. That one prints out a dash before the first tag (if there are any). I use that for a separation from the date that comes in just before it.

I was thinking I'd try to output just the first tag, but after seeing the full list, I'm fine with that. So, this has me in good shape for the tags.

Other Stuff

Reference to the different Hugo tokens that can be used in templates:

<table>
    <tr>
        <td>{{/* */}}</td>
        <td>comment</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td>{{ }}</td>
        <td>output</td>
    </tr>
    <tr>
        <td>{{&lt; &gt;}}</td>
        <td>partials</td>
    </tr>
    <tr>
        <td>{{&#37; &#37;}}</td>
        <td>shortcodes</td>
    </tr>
    <tr>
        <td>{{- -}}</td>
        <td>removes surrounding white space</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>