List all the categories used in the blog

Hi,

I try to list all the categories used in my blog like this:

<ul class="categories">
{{range $name, $taxonomy := .Site.Taxonomies.categories}}
<li><a href="{{$baseurl}}{{"categories/" | relLangURL}}{{$name | urlize}}">{{$name}}</a></li>
{{end}}
</ul>

But I get two problems:

  1. The list works only when I restart $hugo server. When I refresh the page .Site.Taxonomies.categories is empty
  2. When it works, I only get the url of the category but not the name I defined in a _index.md (I can get the title of the categories with .Params.categories in a single page)

Any idea ? Thanks!

That’s odd. I just checked my theme and I’m listing categories pretty much in the same way

{{ range $key, $value := .Site.Taxonomies.categories }}
	<li><a href="{{ $baseurl  }}categories/{{ $key | urlize  }}">{{ $key | humanize }}</a> ({{ len $value }})</li>
{{ end }}

how is your config.toml set up?

Mine is like this:

[taxonomies]
tag = "tags"
category = "categories"

could this be a result of the default fast render mode?

1 Like

By trying to solve my second problem, I solved my first one.
I don’t use .Site.Taxonomies.categories anymore (which was empty most of the time).

{{range ($.Site.GetPage "taxonomyTerm" "categories").Pages }}
   <a href="{{.Permalink}}">{{.Title}}</a></li>
{{end}}

I’m still curious to understand why .Site.Taxonomies.categories doesn’t work well.

2 Likes

I don’t want to open a new thread, so I’ll join in here: The code that @brunoamaral posted unfortunately doesn’t work for me either, although it should. (I use category instead of categories, but everything else is identical.)

Any new ideas?

That’s some pretty old code :slightly_smiling_face:
Here is the version I am using right now.

{{ range $.Site.Taxonomies.categories }}
	{{ if ne .Page.Title "" }}
		<a href="{{ .Page.Permalink | absLangURL }}" class="btn btn-primary" title="{{ i18n "posts_categorized_as" }} {{ .Page.Title }}"><strong>{{ .Page.Title }}</strong> ({{ .Count }})</a>
	{{ end }}
{{ end }}

Hope it helps.

1 Like

Ah! I found my problem thanks to your code. It works now!
(It was a complete misunderstanding on my side - the singular term does not work, the plural term does. Oops!)

1 Like

Y’all do this instead.

{{- with .GetTerms "categories" }}
  {{ range . }}
    <a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a>
  {{- end }}
{{- end }}
1 Like

What’s the technical difference here?

That’s the ‘modern’ way of ranging through taxonomies in hugo

1 Like

TIL. Thanks!

So if I want the whole site’s categories, I’ll need to use Site.GetTerms?

GetTerms is a Page method, not a Site method, and is not applicable to this issue.

1 Like