链接和交叉引用
ref
和 relref
短代码分别显示文档的绝对和相对永久链接。
ref
和 relref
的用法
ref
和 relref
短代码需要一个参数:内容文档的路径,可以带或不带文件扩展名,可以带或不带锚点。不以 /
开头的路径首先相对于当前页面解析,然后相对于站点的其余部分解析。
.
└── content
├── about
| ├── _index.md
| └── credits.md
├── pages
| ├── document1.md
| └── document2.md // has anchor #anchor
├── products
| └── index.md
└── blog
└── my-post.md
页面可以按如下方式引用
{{< ref "document2" >}} <-- From pages/document1.md, relative path
{{< ref "document2#anchor" >}}
{{< ref "document2.md" >}}
{{< ref "document2.md#anchor" >}}
{{< ref "#anchor" >}} <-- From pages/document2.md
{{< ref "/blog/my-post" >}} <-- From anywhere, absolute path
{{< ref "/blog/my-post.md" >}}
{{< relref "document" >}}
{{< relref "document.md" >}}
{{< relref "#anchor" >}}
{{< relref "/blog/my-post.md" >}}
index.md
可以通过其路径或其包含的目录(不带结尾的 /
)引用。 _index.md
只能通过其包含的目录引用
{{< ref "/about" >}} <-- References /about/_index.md
{{< ref "/about/_index" >}} <-- Raises REF_NOT_FOUND error
{{< ref "/about/credits.md" >}} <-- References /about/credits.md
{{< ref "/products" >}} <-- References /products/index.md
{{< ref "/products/index" >}} <-- References /products/index.md
要在 Markdown 中使用 ref
或 relref
生成超链接
[About]({{< ref "/about" >}} "About Us")
如果无法唯一解析文档,Hugo 会发出错误或警告。错误行为是可配置的;请参见下文。
链接到另一个语言版本
使用 ref
或 relref
而不指定语言,将使引用解析为当前内容页面的语言。
要链接到文档的另一个语言版本,请使用此语法
{{< relref path="document.md" lang="ja" >}}
获取另一种输出格式
要链接到文档的另一种输出格式,请使用此语法
{{< relref path="document.md" outputFormat="rss" >}}
标题 ID
使用 Markdown 文档类型时,Hugo 会为页面上的每个标题生成元素 ID。例如
## Reference
生成此 HTML
<h2 id="reference">Reference</h2>
在使用 ref
或 relref
短代码时,通过将 ID 附加到路径来获取标题的永久链接
{{< ref "document.md#reference" >}}
{{< relref "document.md#reference" >}}
通过包含属性来生成自定义标题 ID。例如
## Reference A {#foo}
## Reference B {id="bar"}
生成此 HTML
<h2 id="foo">Reference A</h2>
<h2 id="bar">Reference B</h2>
如果同一标题在页面上出现多次,Hugo 将生成唯一的元素 ID。例如
## Reference
## Reference
## Reference
生成此 HTML
<h2 id="reference">Reference</h2>
<h2 id="reference-1">Reference</h2>
<h2 id="reference-2">Reference</h2>
Ref 和 RelRef 配置
可以在 hugo.toml
中配置该行为
- refLinksErrorLevel (“ERROR”)
- 当使用
ref
或relref
解析页面链接并且无法解析链接时,将使用此日志级别记录。有效值为ERROR
(默认值)或WARNING
。任何ERROR
都会使构建失败 (exit -1
)。 - refLinksNotFoundURL
- 当在
ref
或relref
中找不到页面引用时,用作占位符的 URL。按原样使用。