I wanted to list the categories of a blog post, but couldn’t find a simple solution.
tl;dr
The snippet in orgmode is simply
@@hugo:{{< categories-list >}}@@
The shortcode in the file layouts/shortcodes/categories-list.html
is
<!-- Returns an UL (but still ordered) list of categories of the calling page -->
{{ $BaseURL := .Site.BaseURL }}
<ul>
{{ $taxo := "categories" }}
<!-- Loop over all categories -->
{{range $p := ($.Site.GetPage "taxonomyTerm" $taxo).Pages }}
<!-- Loop over all categories for this page -->
{{ range $page_category := $.Page.Params.categories }}
{{ $wanted_category_link := (printf "%s%s/%s/" $BaseURL $taxo (lower $page_category)) }}
<!-- Check to see if the links match -->
{{ if in $wanted_category_link $p.Permalink }}
<li><a href="{{$p.Permalink}}">{{$p.Title}}</a>{{if $p.Summary}} — {{$p.Summary}}{{end}}</li>
{{ end }}
{{ end }}
{{ end }}
</ul>
What is the result?
Well, this page is part of the following categories:
Caveat emptor
My first attempt at this didn’t have the .Site.BaseURL
reference and I was
using $p.RelPermalink
rather than $p.Permalink
. The code worked for a local
test, but didn’t work when I deployed to GitHub.
The reason was that my URL on GitHub has a trailing /blog
where my local test
URL didn’t and the URL string I was creating missed the /blog
when I deployed
it.
That was a useful lesson.