lemniskett.moe/content/blog/hugo-link-render-hook/index.md

2.6 KiB

title description summary date draft author tags canonicalURL showToc TocOpen TocSide hidemeta comments disableHLJS disableShare hideSummary searchHidden ShowReadingTime ShowBreadCrumbs ShowPostNavLinks ShowWordCount ShowRssButtonInSectionTermList UseHugoToc cover
Hugo Open External Link in New Tab and Add Rel Attribute How to add a render hook for link in Hugo How to add a render hook for link in Hugo 2023-09-10T19:38:50+07:00 false Hiiruki
hugo
render-hook
goldmark
true false right false false true true false false true true true true true false
image alt caption relative hidden
<image path/url> <alt text> <text> false true

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:

<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:

<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