HUGO
Menu
GitHub 87548 stars Mastodon

標題渲染鉤子

創建標題渲染鉤子模板以覆蓋 Markdown 標題到 HTML 的渲染。

上下文

標題_渲染鉤子_ 模板接收以下 上下文

Anchor
(string) 標題元素的 id 屬性。
Attributes
(map) Markdown 屬性,如果您的站點配置如下則可用:
markup:
  goldmark:
    parser:
      attribute:
        title: true
[markup]
  [markup.goldmark]
    [markup.goldmark.parser]
      [markup.goldmark.parser.attribute]
        title = true
{
   "markup": {
      "goldmark": {
         "parser": {
            "attribute": {
               "title": true
            }
         }
      }
   }
}
Level
(int) 標題級別,1 到 6。
Page
(page) 對當前頁面的引用。
PageInner
(page) 對通過 RenderShortcodes 方法嵌套的頁面的引用。詳見
PlainText
(string) 標題文本(純文本形式)。
Text
(template.HTML) 標題文本。

示例

在默認配置中,Hugo 根據 CommonMark 規范 渲染 Markdown 標題,並添加了自動 id 屬性。要創建執行相同操作的渲染鉤子:

layouts/_markup/render-heading.html
<h{{ .Level }} id="{{ .Anchor }}" {{- with .Attributes.class }} class="{{ . }}" {{- end }}>
  {{- .Text -}}
</h{{ .Level }}>

要在每個標題的右側添加錨點鏈接:

layouts/_markup/render-heading.html
<h{{ .Level }} id="{{ .Anchor }}" {{- with .Attributes.class }} class="{{ . }}" {{- end }}>
  {{ .Text }}
  <a href="#{{ .Anchor }}">#</a>
</h{{ .Level }}>

PageInner 詳情

PageInner 的主要用途是相對於包含的 Page 解析鏈接和 頁面資源。例如,創建一個 “include” 短代碼,從多個內容文件組合頁面,同時保留腳注和目錄的全局上下文:

layouts/_shortcodes/include.html
{{ with .Get 0 }}
  {{ with $.Page.GetPage . }}
    {{- .RenderShortcodes }}
  {{ else }}
    {{ errorf "短代碼 %q 無法找到 %q。參見 %s" $.Name . $.Position }}
  {{ end }}
{{ else }}
  {{ errorf "短代碼 %q 需要一個位置參數來指示要包含的文件的邏輯路徑。參見 %s" .Name .Position }}
{{ end }}

然後在您的 Markdown 中調用短代碼:

content/posts/post-1.md
{{% include "/posts/post-2" %}}

在渲染 /posts/post-2 時觸發的任何渲染鉤子將獲得:

  • 調用 Page 時獲得 /posts/post-1
  • 調用 PageInner 時獲得 /posts/post-2

如果不相關,PageInner 會回退到 Page 的值,並且始終返回一個值。

PageInner 方法僅與調用 RenderShortcodes 方法的短代碼相關,並且您必須使用 Markdown 表示法 調用短代碼。

作為實際示例,Hugo 的嵌入式鏈接和圖像渲染鉤子使用 PageInner 方法來解析 Markdown 鏈接和圖像目標。請參閱各自的源代碼:


Last updated: January 1, 0001
Improve this page