RenderShortcodes
语法
PAGE.RenderShortcodes
返回值
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 ...
如果这真的是你想要的,可以关闭上面的警告。