Skip to content

Instantly share code, notes, and snippets.

@bennetthardwick
Created January 19, 2021 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennetthardwick/f0a57ceb5be7460b5755eb4ee41967bc to your computer and use it in GitHub Desktop.
Save bennetthardwick/f0a57ceb5be7460b5755eb4ee41967bc to your computer and use it in GitHub Desktop.
Resolve markdown links in hugo without having to use shortcodes. https://bennetthardwick.com/wiki/hugo/resolve-markdown-links/
{{/* The destination of the link. Bind to a variable for convenience. */}}
{{ $path := .Destination }}
{{/* If the link isn't a relative link or is an outbound link,
don't rewrite /*}}
{{ if or (hasPrefix $path "./") (not (hasPrefix $path "http")) (hasPrefix $path "../") }}
{{ $file := .Page.File.LogicalName }}
{{/* If the link has a hash, extract it */}}
{{ $hash := index (findRE "#(.*)$" $path) 0 }}
{{ if $hash }}
{{ $path = replaceRE (printf "%s$" $hash) "" $path }}
{{ else }}
{{ $hash = "" }}
{{ end }}
{{/* Non-index files are outputted as directories with
index files, so these links need to start with `../` */}}
{{ if and (not (or (eq $file "index.md") (eq $file "_index.md"))) (strings.HasSuffix $file ".md") }}
{{ $path = path.Join "../" $path }}
{{ end }}
{{/* Remove _index / index and make sure link ends with trailing slash */}}
{{ $path = path.Join .Page.RelPermalink $path }}
{{ $path = replaceRE "/index.md$" "/" $path }}
{{ $path = replaceRE "/_index.md$" "/" $path }}
{{ $path = replaceRE ".md$" "/" $path }}
{{ $path = path.Join $path "/" }}
{{ $path = printf "%s/%s" $path $hash }}
{{/* A special case for the wiki, if the link starts with
a hash it's a tag, so style it differently */}}
{{ $tag := hasPrefix .Text "#" }}
<a class="ref{{ if $tag }}tag{{end}}"href="{{ $path | safeURL }}">{{ .Text | safeHTML }}</a>
{{ else }}
<a href="{{ .Destination | safeURL }}" target="_blank" rel="noreferrer">{{ .Text | safeHTML }}</a>
{{ end }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment