Breadcrumb partial with structured data

Creating a breadcrumbs-list is unfortunatley not a built in function from Hugo. In this article you find a way to create breadcrumbs including structured data with the power of partials.

List breadcrumbs in a template

{{ $siteUrl := replace .Permalink ( printf "%s" .Site.BaseURL) "" }}
{{ $.Scratch.Add "sitePath" .Site.BaseURL }}

{{ $.Scratch.Add "siteBreadcrumbs" (slice (dict "url" .Site.BaseURL "name" "home" "position" 1 )) }}
{{ range $index, $element := split $siteUrl "/" }}
{{ $.Scratch.Add "sitePath" $element }}
{{ $.Scratch.Add "sitePath" "/" }}
{{ if ne $element "" }}
{{ $.Scratch.Add "siteBreadcrumbs" (slice (dict "url" ($.Scratch.Get "sitePath") "name" . "position" (add $index 2))) }}
{{ end }}
{{ end }}

<nav class="breadcrumbs">
    <ul>
        {{ range $.Scratch.Get "siteBreadcrumbs" }}
        <li><a href="{{ .url }}">{{ .name }}</a></li>
        {{ end }}
    </ul>
</nav>

Structured Data with LD-JSON

{{ $url := replace .Permalink ( printf "%s" .Site.BaseURL) "" }}
{{ $.Scratch.Add "path" .Site.BaseURL }}

{{ $.Scratch.Add "breadcrumb" (slice (dict "url" .Site.BaseURL "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>