Using nofollow links in Hugo's Markdown

I seem to have more posts about nofollow links than actual nofollow links, but here’s one more.

Markdown doesn’t support nofollow links by default, so you either have to write them in HTML or tweak your template to handle them.

Update: after reviewing the options, I ended up using a bounce-URL instead.

This is kinda simple. Just write HTML directly in markdown: anchor

<a href="" rel="nofollow">anchor</a>

There are probably easier ways to do this, but I didn’t spot any off-hand. In Markdown, links are written like this:


Without changing Markdown, my approach is to just add an unnecessary component that doesn’t break if you get the code wrong. I can then check for this component when the markdown is processed and swap out the link element as needed. I picked #? added to the end of the URL. I don’t think this is actively used for anything else online, so it’s unlikely that I’ll run into clashes (also, this is my site, so I don’t really care :-)).

In short, the new links look like this for nofollow:


To convert them into HTML, in Hugo you can add a render-link.html file which is processed (note to self: make sure you have a recent version of Hugo installed). This file is in /themes/your-theme-name/layouts/_default/_markup/ (or potentially somewhere directly too). This file is processed whenever a link is rendered, so you might already have something in there.

I’m not used to the format, so my approach is probably a bit clumsy. But it works. This one will also add a target=_blank, rel=noopener, and class=external to any external links.

Here’s my render-link.html (Github Gist):

{{- $linkurl := .Destination }}
{{- $relval := ""}}
{{- $targetval := ""}}
{{- $classval := "" }}
{{- if strings.HasPrefix $linkurl "http" }}
    {{- $targetval = printf "%s %s"  $targetval "_blank" }}
    {{- $relval = printf "%s %s" $relval "noopener" }}
    {{- $classval = printf "%s %s" $classval "external" }}
{{- end -}}
{{- if strings.HasSuffix $linkurl "#?" }} 
    {{- $relval = printf "%s %s" $relval "nofollow" }}
    {{- $urlparts := split $linkurl "#" -}}
    {{- $linkurl = index $urlparts 0}}
{{- end -}}
<a href="{{ $linkurl | safeURL }}"
    {{- with .Title}} title="{{ trim . " " }}"{{ end -}}
    {{- with $relval}} rel="{{ trim . " " }}"{{ end -}}
    {{- with $targetval}} target="{{ trim . " " }}"{{ end -}}
    {{- with $classval}} class="{{ trim . " " }}"{{ end -}}
>{{ .Text | safeHTML }}</a>

Additionally, I have this in my CSS file:

	border-bottom: dashed 2px #ffa500;

  content: "\21AA\A0"; /* right hook / non-breaking space */

Testing some links:

Comments / questions

There's currently no commenting functionality here. If you'd like to comment, please use Twitter and @me there. Thanks!

Tweet about this - and/or - search for latest comments / top comments

Related pages