传递渲染钩子
概述
Hugo 使用 Goldmark 将 Markdown 渲染为 HTML。Goldmark 支持自定义扩展来扩展其核心功能。Goldmark 传递扩展捕获并保留分隔文本片段内的原始 Markdown,包括分隔符本身。这些被称为传递元素。
根据您选择的分隔符,Hugo 将传递元素分类为块或内联。考虑这个人为的例子
This is a
\[block\]
passthrough element with opening and closing block delimiters.
This is an \(inline\) passthrough element with opening and closing inline delimiters.
更新您的站点配置以启用传递扩展,并为每种传递元素类型(block
或 inline
)定义开始和结束分隔符。例如
markup:
goldmark:
extensions:
passthrough:
delimiters:
block:
- - \[
- \]
- - $$
- $$
inline:
- - \(
- \)
enable: true
[markup]
[markup.goldmark]
[markup.goldmark.extensions]
[markup.goldmark.extensions.passthrough]
enable = true
[markup.goldmark.extensions.passthrough.delimiters]
block = [['\[', '\]'], ['$$', '$$']]
inline = [['\(', '\)']]
{
"markup": {
"goldmark": {
"extensions": {
"passthrough": {
"delimiters": {
"block": [
[
"\\[",
"\\]"
],
[
"$$",
"$$"
]
],
"inline": [
[
"\\(",
"\\)"
]
]
},
"enable": true
}
}
}
}
}
在上面的示例中,有两组 block
分隔符。您可以在 Markdown 中使用其中任何一个。
Goldmark 传递扩展通常与 MathJax 或 KaTeX 显示引擎结合使用,以渲染使用 数学表达式,这些表达式以 LaTeX 或 Tex 编写。
要启用传递元素的自定义渲染,请创建一个渲染钩子。
上下文
传递渲染钩子模板接收以下 上下文
属性
(map
) Markdown 属性,如果您按如下方式配置您的站点,则可用
markup:
goldmark:
parser:
attribute:
block: true
[markup]
[markup.goldmark]
[markup.goldmark.parser]
[markup.goldmark.parser.attribute]
block = true
{
"markup": {
"goldmark": {
"parser": {
"attribute": {
"block": true
}
}
}
}
}
Hugo 为块传递元素填充 Attributes
映射。Markdown 属性不适用于内联元素。
内部
(string
) 传递元素的内部内容,不包括分隔符。
序号
(int
) 页面上传递元素的从零开始的序号。
页面
(page
) 对当前页面的引用。
PageInner
(page
) 通过 RenderShortcodes
方法嵌套的页面的引用。查看详情。
位置
(string
) 传递元素在页面内容中的位置。
类型
(string
) 传递元素类型,block
或 inline
。
示例
作为使用 MathJax 或 KaTeX 显示引擎渲染数学表达式的替代方案,可以创建一个 passthrough 渲染钩子,该钩子调用 transform.ToMath
函数。
{{ if eq .Type "block" }}
{{ $opts := dict "displayMode" true }}
{{ transform.ToMath .Inner $opts }}
{{ else }}
{{ transform.ToMath .Inner }}
{{ end }}
虽然您可以使用如上所示的带有条件逻辑的模板,但您也可以为每种 passthrough 元素的 Type
创建单独的模板。
layouts/
└── _default/
└── _markup/
├── render-passthrough-block.html
└── render-passthrough-inline.html
PageInner 详情
v0.125.0 版本新增PageInner
的主要用例是解析相对于包含的 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
不相关,则会回退到 Page
的值,并且始终返回一个值。
作为一个实际示例,Hugo 的嵌入链接和图像渲染钩子使用 PageInner
方法来解析 markdown 链接和图像目标。请查看每个的源代码: