{{ with .Params.canonical_url -}}

<link rel="canonical" href="{{ . }}">

{{- else -}}

  {{ $canonicalURL := .Permalink -}}

  {{ $defaultLang := "en" -}}
  {{ if and (ne .Language.Lang $defaultLang) .File -}}
    {{/* This page is in a non-default-language section */ -}}
    {{ $pagePath := strings.TrimPrefix (add hugo.WorkingDir "/content/") .File.Filename -}}
    {{ if hasPrefix $pagePath $defaultLang -}}

      {{/* This page is actually a default-language fallback page. Use the link
      to the origin of the fallback page as canonical reference. */ -}}

      {{ $translationPages := where .Translations "Lang" $defaultLang -}}
      {{ $translation := index $translationPages 0 -}}
      {{ with $translation -}}
        {{ $canonicalURL = .Permalink -}}
      {{ end -}}
    {{ end -}}
  {{ end -}}
  <link rel="canonical" href="{{ $canonicalURL }}">

{{- end -}}
