链接渲染钩子
Markdown
Markdown 链接包含三个组成部分:链接文本、链接目标和可选的链接标题。
[Post 1](/posts/post-1 "My first post")
------ ------------- -------------
text destination title
这些组成部分将传递到渲染钩子 上下文 ,如下所示。
上下文
链接渲染钩子模板接收以下上下文:
目标
(string
) 链接目标。
页面
(page
) 对当前页面的引用。
页面内部
New in v0.125.0(page
) 对通过 RenderShortcodes
方法嵌套的页面的引用。 查看详情 。
纯文本
(string
) 链接描述,纯文本格式。
文本
(template.HTML
) 链接描述。
标题
(string
) 链接标题。
示例
在默认配置中,Hugo 根据 CommonMark 规范 渲染 Markdown 链接。要创建执行相同操作的渲染钩子:
<a href="{{ .Destination | safeURL }}"
{{- with .Title }} title="{{ . }}"{{ end -}}
>
{{- with .Text }}{{ . }}{{ end -}}
</a>
{{- /* chomp trailing newline */ -}}
要为外部链接包含设置为 external
的 rel
属性:
{{- $u := urls.Parse .Destination -}}
<a href="{{ .Destination | safeURL }}"
{{- with .Title }} title="{{ . }}"{{ end -}}
{{- if $u.IsAbs }} rel="external"{{ end -}}
>
{{- with .Text }}{{ . }}{{ end -}}
</a>
{{- /* chomp trailing newline */ -}}
默认值
New in v0.123.0Hugo 包含一个 嵌入式链接渲染钩子 来解析 Markdown 链接目标。默认情况下禁用,您可以在站点配置中启用它:
markup:
goldmark:
renderHooks:
link:
enableDefault: true
[markup]
[markup.goldmark]
[markup.goldmark.renderHooks]
[markup.goldmark.renderHooks.link]
enableDefault = true
{
"markup": {
"goldmark": {
"renderHooks": {
"link": {
"enableDefault": true
}
}
}
}
}
自定义渲染钩子,即使由主题或模块提供,也会覆盖嵌入式渲染钩子,而不管上面的配置设置如何。
嵌入式链接渲染钩子通过查找匹配的页面来解析内部 Markdown 目标,然后回退到匹配的 页面资源 ,然后回退到匹配的 全局资源 。远程目标将被传递,如果无法解析目标,渲染钩子不会抛出错误或警告。
您必须将全局资源放在 assets 目录中。如果您已将资源放在 static 目录中,并且您无法或不愿意移动它们,则必须通过在站点配置中包含这两个条目将 static 目录挂载到 assets 目录:
module:
mounts:
- source: assets
target: assets
- source: static
target: assets
[module]
[[module.mounts]]
source = 'assets'
target = 'assets'
[[module.mounts]]
source = 'static'
target = 'assets'
{
"module": {
"mounts": [
{
"source": "assets",
"target": "assets"
},
{
"source": "static",
"target": "assets"
}
]
}
}
PageInner 详情
New in v0.125.0PageInner
的主要用例是解析相对于已包含的 Page
的链接和 页面资源 。例如,创建一个“include”短代码,从多个内容文件组合一个页面,同时保留脚注和目录的全局上下文:
{{ with .Get 0 }}
{{ with $.Page.GetPage . }}
{{- .RenderShortcodes }}
{{ else }}
{{ errorf "The %q shortcode was unable to find %q. See %s" $.Name . $.Position }}
{{ end }}
{{ else }}
{{ errorf "The %q shortcode requires a positional parameter indicating the logical path of the file to include. See %s" .Name .Position }}
{{ end }}
然后在你的Markdown中调用短代码:
{{% include "/posts/p2" %}}
在渲染 /posts/p2
期间触发的任何渲染钩子将获得:
- 调用
Page
时为/posts/p1
- 调用
PageInner
时为/posts/p2
如果与 PageInner
不相关,则 PageInner
回退到 Page
的值,并始终返回值。
作为一个实际示例,Hugo的嵌入式链接和图像渲染钩子使用 PageInner
方法来解析Markdown链接和图像目标。查看每个源代码: