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