Lego2012
5/18/2017 - 6:08 AM

Breadcrumb Partial with Structured Data

Breadcrumb Partial with Structured Data

<!-- 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>
{{ $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>