Hugo设置站外链接新窗口打开

Markdown语法中,超链接可以指定锚文本、链接地址和Title属性,写法如下:

[锚文本](链接地址 "Title属性")

没有更多了,如果想要指定该链接在新窗口打开,也就是target属性,只能直接在Markdown中写HTML标签。

对于Hugo,可以使用Markdown Render Hooks在渲染Markdown时为站外链接添加target属性。

超链接Hooks的模板文件路径为:

_default/_markup/render-link.html

模板内容如下:

<a href="{{ .Destination }}"
{{- if not (strings.HasPrefix .Destination (absURL "")) }} target="_blank" rel="noopener"{{ end -}}
>{{ .Text }}</a>

相关变量/函数说明:

  • .Destination变量为超链接URL;
  • absURL函数返回网站的首页地址;
  • .Text变量为锚文本;

使用了strings.HasPrefix方法检测超链接URL中是否包含了网站首页地址,如果没有包含就说明是站外链接,则添加target属性和rel属性。

阿里云