HUGO
Menu
GitHub 87548 stars Mastodon

RenderShortcodes

渲染給定頁面內容中的所有短代碼,保留周圍的標記。

Syntax

PAGE.RenderShortcodes

Returns

template.HTML

短代碼 模板中使用此方法從多個內容文件構建頁面,同時保留腳注和目錄的全局上下文。

例如:

layouts/_shortcodes/include.html
{{ with .Get 0 }}
  {{ with $.Page.GetPage . }}
    {{- .RenderShortcodes }}
  {{ else }}
    {{ errorf "The %q shortcode was unable to find %q. See %s" $.Name . $.Position }}
  {{ end }}
{{ else }}
  {{ errorf "The %q shortcode requires a positional parameter indicating the logical path of the file to include. See %s" .Name .Position }}
{{ end }}

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

content/about.md
{{% include "/snippets/services" %}}
{{% include "/snippets/values" %}}
{{% include "/snippets/leadership" %}}

每個包含的 Markdown 文件都可以包含對其他短代碼的調用。

短代碼表示法

在上面的示例中,重要的是理解調用短代碼時使用的兩個分隔符之間的區別:

  • {{< myshortcode >}} 告訴 Hugo 渲染的短代碼不需要進一步處理。例如,短代碼內容是 HTML。
  • {{% myshortcode %}} 告訴 Hugo 渲染的短代碼需要進一步處理。例如,短代碼內容是 Markdown。

對於上面描述的 “include” 短代碼,請使用後者。

進一步解釋

要了解 RenderShortcodes 方法返回的內容,請考慮此內容文件

content/about.md
+++
title = 'About'
date = 2023-10-07T12:28:33-07:00
+++

{{< ref "privacy" >}}

An *emphasized* word.

使用此模板代碼:

{{ $p := site.GetPage "/about" }}
{{ $p.RenderShortcodes }}

Hugo 渲染此內容:

https://example.org/privacy/

An *emphasized* word.

請注意,內容文件中的短代碼已渲染,但保留了周圍的 Markdown。

限制

.RenderShortcodes 的主要用例是包含 Markdown 內容。如果您嘗試在 Markdown 內的 HTML 塊中使用 .RenderShortcodes,您將收到類似以下的警告:

WARN .RenderShortcodes detected inside HTML block in "/content/mypost.md"; this may not be what you intended ...

如果這確實是您想要的,可以關閉上述警告。


Last updated: January 1, 0001
Improve this page