Fragments
New in v0.111.0
在 URL 中,無論是絕對路徑還是相對路徑,fragment
都指向頁面中某個 HTML 元素的 id
屬性。
/articles/article-1#section-2
------------------- ---------
路徑 片段
Hugo 在頁面內容中的每個 Markdown ATX 和 setext 標題上賦予一個 id
屬性。您也可以根據需要通過 [Markdown 屬性] 覆蓋此 id
。這樣就創建了目錄條目(TOC)與頁面標題之間的關係。
使用 Page
物件上的 Fragments
方法來創建目錄,方法之一是使用 Fragments.ToHTML
方法,或通過 [walk] Fragments.Map
數據結構進行處理。
方法
Headings
: (map
)頁面上所有標題的嵌套映射。每個映射包含以下鍵:ID
、Level
、Title
和 Headings
。要檢查數據結構:
<pre>{{ debug.Dump .Fragments.Headings }}</pre>
HeadingsMap
: (slice
)頁面上所有標題的映射切片,其中包含每個標題的第一級鍵。每個映射包含以下鍵:ID
、Level
、Title
和 Headings
。要檢查數據結構:
<pre>{{ debug.Dump .Fragments.HeadingsMap }}</pre>
Identifiers
: (slice
)包含頁面上每個標題 id
的切片。要檢查數據結構:
<pre>{{ debug.Dump .Fragments.Identifiers }}</pre>
Identifiers.Contains ID
: (bool
)報告頁面上是否有一個或多個標題擁有給定的 id
屬性,這在 render hook 中驗證碎片時很有用。
{{ .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>