How to localize permalinks in Hugo: a workaround
And a word or two on going open source
When working with Hugo’s multilingual mode, it’s nothing but natural to wonder whether it exists a direct way to localize (i.e. translate) the permalinks.
I couldn’t find a direct way to achieve it. Fortunately, it does exist a simple way to do it, which I’ll cover here.
This article assumes the following prerequisites, which the solution was tested with. Other configurations should also work after a few tweaks (or none at all).
- Hugo >=
0.101
I’m sure this version is way too high for what we’re trying to achieve. - A Hugo site.
- A default language set in the config file:
defaultContentLanguage = <language-code>
- A translation by filename structure.
- Some content which permalinks we want to localize.
For this tutorial I’ll use the source code of this article itself. You can find it here.
1. Enable slugorfilename
in the config file
Navigate to your config file and under the Permalinks section set the posts
field to slugorfilename
:
|
|
2. Set a proper slug in the front matter of your content files
This article (and the whole website) has two versions: one in English and one in Spanish.
The English filename is index.en.md
,
whereas the Spanish one is index.es.md
.
We need to set a slug for each of them,
since is not possible to set only the English one and then translate it to Spanish.
For the English one, in the front matter:
|
|
For the Spanish one:
|
|
So far, so good.
When the site is built, the English content is accesible via /localizing-permalinks/
and the Spanish content can be reached by following /es/traducir-enlaces
.
But what happens if we request /traducir-enlaces/
or /es/localizing-permalinks
?
We can go a step further and improve the website’s behavior by using aliases.
3. [Optional] Use aliases to redirect the translated content
The content it’s already linked by Hugo since we’re using a translation by filename approach. But if a curious reader (or a bilingual one) wants to access the corresponding translation by typing in the permalink, they will receive an error.
To fix that, we add the following in the front matter:
index.en.md
|
|
index.es.md
|
|
That way the slugs will redirect properly.
A closing thought on going open source
I started this website a few days ago (first post here) and from the beginning I was sure that I wanted it to be open source. In short, that means that the code for building this site is publicly available here.
There are a few reasons for that:
- I love open source. Most of the things I know about development I learned from others, by reading articles or diving in their codebases.
- This is a solo project, but that doesn’t mean it has to be a mess. Being open source pushes me to adopt a set of best practices and stick to them.
- It’s a great way to showcase my learning path.