HUGO
Menu
GitHub 87548 stars Mastodon

Fragments

返回给定页面中片段的数据结构。

Syntax

PAGE.Fragments

Returns

tableofcontents.Fragments

在 URL(无论是绝对还是相对)中,片段 链接到页面上 HTML 元素的 id 属性。

/articles/article-1#section-2
------------------- ---------
       path         fragment

Hugo 为页面内容中的每个 Markdown ATXsetext 标题分配一个 id 属性。您可以根据需要使用 Markdown 属性 覆盖 id。这在 目录 (TOC) 中的条目和页面上的标题之间创建关系。

Page 对象上使用 Fragments 方法,通过 Fragments.ToHTML 方法创建目录,或 遍历 Fragments.Map 数据结构。

方法

Headings

(slice) 页面上所有标题的切片,每个标题有第一级键。每个映射包含以下键:IDLevelTitleHeadings。要检查数据结构:

<pre>{{ debug.Dump .Fragments.Headings }}</pre>

HeadingsMap

(map) 页面上所有标题的嵌套映射。每个映射包含以下键:IDLevelTitleHeadings。要检查数据结构:

<pre>{{ debug.Dump .Fragments.HeadingsMap }}</pre>

Identifiers

(slice) 包含页面上每个标题的 id 属性的切片。如果配置了,还将包含页面上每个描述术语(即 dt 元素)的 id 属性。

详见 配置 Markup

要检查数据结构:

<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) 返回目录作为嵌套列表,有序或无序,与 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>

在渲染钩子中使用 Fragments 方法是安全的,即使对于当前页面也是如此。

在短代码中使用 Fragments 方法时,使用 标准记法 调用短代码。如果您使用 Markdown 记法,渲染的短代码将包含在片段映射的创建中,导致循环。


Last updated: January 1, 0001
Improve this page