After quite a while searching I’ve found this article with a very nice way to implement Breadcrumbs with Hugo.
I modified it a little bit to not add links to every part and make use of i18n (since I think I wouldn’t be able to access FrontMatters from here) but also to apply a small workaround to remove some unwanted trails that didn’t match a translated entry:
{{- $url := replace .Permalink ( printf "%s" ( "/" | absLangURL ) ) "" -}}
{{- $url := replace .Permalink ( printf "%s" ( "/" | absLangURL ) ) "" -}}
{{- $.Scratch.Add "path" ( "/" | absLangURL ) -}}
{{- $.Scratch.Add "breadcrumb" (slice (dict "url" ( "/" | absLangURL ) "name" "home" "position" 1 )) -}}
{{- range $index, $element := split $url "/" -}}
{{- $.Scratch.Add "path" $element -}}
{{- $.Scratch.Add "path" "/" -}}
{{- if ne $element "" -}}
{{- $.Scratch.Add "breadcrumb" (slice (dict "url" ($.Scratch.Get "path") "name" . "position" (add $index 2))) -}}
{{- end -}}
{{- end -}}
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{{ range $.Scratch.Get "breadcrumb" }}{{ if ne .position 1 }},{{ end }}{
"@type": "ListItem",
"position": {{ .position }},
"item": {
"@id": "{{ .url }}",
"name": "{{ .name }}"
}
}{{ end }}]
}
</script>
<nav class="breadcrumb">
{{- $length := len ($.Scratch.Get "breadcrumb") -}}
{{- range $index, $.Scratch.Get "breadcrumb" -}}
<!--
Assigning a constant as default value for i18n function
if it doesn't match any entry
Then check if current Breadcrumb item matches this constant,
which means that part shouldn't be one of Breadcrumb's trail
-->
{{- $i18n := i18n ( print "breadcrumbs-" .name ) | default "__INTERNAL__" -}}
{{- if not ( eq ($i18n) "__INTERNAL__" ) -}}
{{ if eq ( (int .position) ) $length }}
<span class="breadcrumb-item active">{{ $i18n }}</span>
{{- else -}}
<a class="breadcrumb-item" href="{{ .url }}" >{{ $i18n }}</a>
{{- end -}}
{{- end -}}
{{ end }}
</nav>
It worked nicely when viewing the site with a language parameter present in URL (i.e. /pt, /fr, /jp…) but when accessing the default language (en), that doesn’t appear in the URL, everything gets duplicated.
First I thought it could be the fact .Site.BaseURL was being used so I replaced it with ( "/" | absLangURL ) but it didn’t change anything.
So… 1) if this article is old 2) this have been discussed here 3) I have searched and tried every implementation of all other questions regarding this matter I could find 4) I am using the latest version - and this still doesn’t work, what should I do then? (ง’̀-'́)ง
Although I don’t think so, after all the breadcrumbs work beforenavigating through the Pagination, here’s my content directory structure if that matters at all:
Thanks @magnusthorek , i use snippet provided in hugo documentation page, i modified it using len to figuring out the length of splitted url to get the $position.