How to support multiligual links to tags and categories in Hugo ?

· · 485 words · 3 minute read

I faced this issue in my custom Hugo theme. I use kmt theme on this website you are reading on. It is bilingual. You find blog posts in English and their translations in Arabic. But when I click on a tag in the Arabic part of the website, it is 404 NOT FOUND ! what?!

The problem is that the tag link is /tags/the-tag-itself but to work it needs to be /ar/tags/the-tag-itself. So, I knew it is a translation support problem.

I was using this code to show tags and categories.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{{ with .Params.tags }}
<div class="tags">
    {{ T "tags" }}:
    {{ range . }}
        <a href="{{ "tags/" | relURL }}{{ . | urlize }}">{{ . }}</a>
    {{ end }}
</div>
{{ end}}

{{ with .Params.categories }}
    <div class="categories">
    {{ T "categories" }}:
    {{ range . }}
        <a href="{{ "categories/" | relURL }}{{ . | urlize }}">{{ . }}</a>
    {{ end }}
    </div>
{{ end}}

Non-scalable, Manual Solution 🔗

I thought of a way to construct the final URL like this.

1
{{ printf "%s/%s" .Lang "tags" | absURL }}{{ . | urlize }}

But I thing this fix will come to bite me later. So, I read more on Hugo documentation website, and found another way to list the tags and categories in idiomatic way.

Hugo idiomatic way 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{ range .GetTerms "tags" }}
    <a href="{{ .RelPermalink }}">
    {{- .LinkTitle -}}
    </a>
{{ end }}

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

I got this code snippet from Hugo docs . This code is elegant, idiomatic and succinct.

But I wanna show the section of tags if there is at least one tag. And the same for categories.

I rewrote this code using with as you can see below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{{ with .GetTerms "tags" }}
<div class="tags">
    {{ T "tags" }}:
    {{ range . }}
    <a href="{{ .RelPermalink }}">
        {{- .LinkTitle -}}
    </a>
    {{ end }}
</div>
{{ end }}

And the code for categories is.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{{ with .GetTerms "categories" }}
<div class="categories">
    {{ T "categories" }}:
    {{ range . }}
    <a href="{{ .RelPermalink }}">
        {{- .LinkTitle -}}
    </a>
    {{ end }}
</div>
{{ end }}

You can see this code as the kmt theme project is open source . Feel free to edit or suggest edit and improvements.

I hope this post helps you. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , Facebook , Telegram and GitHub .

Share: