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 ...
如果这就是你真正想要的,则可以关闭上述警告。