Snippet - partial for creating breadcrumbs (uses Bootstrap 4)

The following snippet creates a breadcrumb trail based on the section/page hierarchy. The depth of hierarchy is controlled by the depth of the nested statements in the middle of the snippet:

{{ with .Parent }}
            {{ $breadcrumbs = $breadcrumbs | append (.Path) }}

I have tested this fairly thoroughly, but your mileage may vary…

<nav id="navbar-dcmi-breadcrumbs" class="" aria-label="breadcrumb">
  <ol class="breadcrumb ml-auto breadcrumb-dcmi">
    {{ if eq .Kind "home"}}
      <li class="breadcrumb-item">Home</li>
    {{ else if (or (eq .Kind "section") (eq .Kind "page")) }}
      {{ $breadcrumbs := (slice .Path) }}
      {{ with .Parent }}
        {{ $breadcrumbs = $breadcrumbs | append (.Path) }}
        {{ with .Parent }}
          {{ $breadcrumbs = $breadcrumbs | append (.Path) }}
          {{ with .Parent }}
            {{ $breadcrumbs = $breadcrumbs | append (.Path) }}
            {{ with .Parent }}
              {{ $breadcrumbs = $breadcrumbs | append (.Path) }}
              {{ with .Parent }}
                {{ $breadcrumbs = $breadcrumbs | append (.Path) }}
              {{ end }}
            {{ end }}
          {{ end }}
        {{ end }}
      {{ end }}
      {{ range (seq (sub (len $breadcrumbs) 1) 0)}}
        {{ $page := $.Site.GetPage (index $breadcrumbs .) }}
        {{ if gt . 0 }}
          <li class="breadcrumb-item"><a href="{{ $page.Permalink }}">{{ $page.Title }}</a></li>
        {{ else }}
          <li class="breadcrumb-item">{{ $page.Title }}</li>
        {{ end }}
      {{ end }}
    {{ else if eq .Kind "taxonomy" }}
      <li class="breadcrumb-item"><a href="/">Home</a></li>
      <li class="breadcrumb-item"><a href="/{{.Data.Plural}}">{{title .Data.Plural}}</a></li>
      <li class="breadcrumb-item">{{ .Title }}</li>
    {{ else if eq .Kind "taxonomyTerm" }}
      <li class="breadcrumb-item"><a href="/">Home</a></li>
      <li class="breadcrumb-item">{{title .Data.Plural}}</li>
    {{ end }}
  </ol>
</nav>
1 Like

Here is a simple recursive breadcrumb. You have to modify it, but the recursive solution seems to be better…

{{ define "breadcrumb" }}
  {{ with .Parent }}
    {{ template "breadcrumb" . }}
    <a href="{{ .URL }}">{{ if .IsHome }}Home{{ else }}{{.Title}}{{ end }}</a> >
  {{ end }}
{{ end }}
{{ if not .IsHome }}
  <div class="breadcrumb">
    {{ template "breadcrumb" . }}
    {{.Title}}
  </div>
{{ end }
2 Likes

I like your recursive solution, but I am not sure how to implement. I am not familiar with the {{ template “breadcrumb” }} syntax. Any tips?

Put your partial code in /layouts/partials/breadcrumb.html. For example my recursive code.

Then use {{ partial "breadcrumb.html" . }} in any layout. With the . (dot) for the context.

Good solution. But fix last line from {{ end } to {{ end }}. Thank you!