片段
语法
PAGE.Fragments
返回值
tableofcontents.Fragments
在 URL 中,无论是绝对 URL 还是相对 URL,片段链接到页面上 HTML 元素的 id
属性。
/articles/article-1#section-2
------------------- ---------
path fragment
Hugo 为页面内容中的每个 Markdown ATX 和 setext 标题分配一个 id
属性。 您可以根据需要使用 Markdown 属性覆盖 id
。 这在 目录 (TOC) 中的条目和页面上的标题之间创建了关系。
在 Page
对象上使用 Fragments
方法,使用 Fragments.ToHTML
方法创建目录,或者通过 遍历 Fragments.Map
数据结构。
方法
- 标题
- (
slice
) 页面上所有标题的映射切片,每个标题都有第一级键。每个映射包含以下键:ID
、Level
、Title
和Headings
。 要检查数据结构
<pre>{{ debug.Dump .Fragments.Headings }}</pre>
- HeadingsMap
- (
map
) 页面上所有标题的嵌套映射。每个映射包含以下键:ID
、Level
、Title
和Headings
。 要检查数据结构
<pre>{{ debug.Dump .Fragments.HeadingsMap }}</pre>
- 标识符
- (
slice
) 包含页面上每个标题的id
的切片。要检查数据结构
<pre>{{ debug.Dump .Fragments.Identifiers }}</pre>
- Identifiers.Contains ID
- (
bool
) 报告页面上的一个或多个标题是否具有给定的id
属性,用于验证链接 渲染钩子中的片段。
{{ .Fragments.Identifiers.Contains "section-2" }} → true
- Identifiers.Count ID
- (
int
) 页面上具有给定id
属性的标题数,用于检测重复项。
{{ .Fragments.Identifiers.Count "section-2" }} → 1
- ToHTML
- (
template.HTML
) 返回一个嵌套列表形式的 TOC,可以是有序列表或无序列表,与TableOfContents
方法返回的 HTML 相同。此方法接受三个参数:起始级别 (int
),结束级别 (int
) 和一个布尔值 (true
返回有序列表,false
返回无序列表)。
当您想要独立于站点配置中的目录设置控制起始级别、结束级别或列表类型时,请使用此方法。
{{ $startLevel := 2 }}
{{ $endLevel := 3 }}
{{ $ordered := true }}
{{ .Fragments.ToHTML $startLevel $endLevel $ordered }}
Hugo 将其渲染为
<nav id="TableOfContents">
<ol>
<li><a href="#section-1">Section 1</a>
<ol>
<li><a href="#section-11">Section 1.1</a></li>
<li><a href="#section-12">Section 1.2</a></li>
</ol>
</li>
<li><a href="#section-2">Section 2</a></li>
</ol>
</nav>