skip to content
Hiiruki's lab

Hugo Open External Link in New Tab and Add Rel Attribute

/ 1 min read

Table of Contents

Hugo is using goldmark as its markdown renderer and has a render hook feature.

Previously, Hugo uses Blackfriday as its markdown renderer in version below v0.60.0. Check the changelog for more information.

Method 1 (No JavaScript)

Make a file layouts/_default/_markup/render-link.html and add the following code:

render-link.html
<a href="{{ .Destination | safeURL }}"
{{ with .Title}} title="{{ . }}"{{ end }}
{{ if strings.HasPrefix .Destination "http" }}
target="_blank" rel="external nofollow noopener noreferrer"
{{ end }}>
{{ .Text | safeHTML }}
</a>

Method 2 (JavaScript)

Make a file layouts/partials/extend_head.html and add the following code:

extend_head.html
<script>
document.addEventListener('DOMContentLoaded', function () {
var links = document.getElementsByTagName("a");
var i;
for (i = 0; i < links.length; i++) {
if (location.hostname !== links[i].hostname) {
links[i].rel = "external nofollow noopener noreferrer";
links[i].target = "_blank";
}
}
});
</script>

References