内部
语法
SHORTCODE.Inner
返回值
template.HTML
此内容
content/services.md
{{< card title="Product Design" >}}
We design the **best** widgets in the world.
{{< /card >}}
使用此短代码
layouts/shortcodes/card.html
<div class="card">
{{ with .Get "title" }}
<div class="card-title">{{ . }}</div>
{{ end }}
<div class="card-content">
{{ .Inner | strings.TrimSpace }}
</div>
</div>
渲染为
<div class="card">
<div class="card-title">Product Design</div>
<div class="card-content">
We design the **best** widgets in the world.
</div>
</div>
使用 RenderString
让我们修改上面的示例,以通过 Page
对象上的 RenderString
方法传递 Inner
返回的值
layouts/shortcodes/card.html
<div class="card">
{{ with .Get "title" }}
<div class="card-title">{{ . }}</div>
{{ end }}
<div class="card-content">
{{ .Inner | strings.TrimSpace | .Page.RenderString }}
</div>
</div>
Hugo 将其渲染为
<div class="card">
<div class="card-title">Product design</div>
<div class="card-content">
We produce the <strong>best</strong> widgets in the world.
</div>
</div>
您可以使用 markdownify
函数代替 RenderString
方法,但后者更灵活。请参阅详情。
备用表示法
不要使用 {{< >}}
表示法调用短代码,而要使用 {{% %}}
表示法
content/services.md
{{% card title="Product Design" %}}
We design the **best** widgets in the world.
{{% /card %}}
当您使用 {{% %}}
表示法时,Hugo 会将整个短代码渲染为 Markdown,需要进行以下更改。
首先,配置渲染器以允许 Markdown 中包含原始 HTML
hugo.
markup:
goldmark:
renderer:
unsafe: true
[markup]
[markup.goldmark]
[markup.goldmark.renderer]
unsafe = true
{
"markup": {
"goldmark": {
"renderer": {
"unsafe": true
}
}
}
}
如果您控制内容,则此配置并非不安全。阅读有关 Hugo 的安全模型的更多信息。
其次,因为我们将整个短代码渲染为 Markdown,我们必须遵守 缩进 和包含 原始 HTML 块 的规则,如 CommonMark 规范中所提供。
layouts/shortcodes/card.html
<div class="card">
{{ with .Get "title" }}
<div class="card-title">{{ . }}</div>
{{ end }}
<div class="card-content">
{{ .Inner | strings.TrimSpace }}
</div>
</div>
此示例与前一个示例之间的差异很细微,但却是必需的。请注意缩进的变化、空白行的添加以及 RenderString
方法的删除。
--- layouts/shortcodes/a.html
+++ layouts/shortcodes/b.html
@@ -1,8 +1,9 @@
<div class="card">
{{ with .Get "title" }}
- <div class="card-title">{{ . }}</div>
+ <div class="card-title">{{ . }}</div>
{{ end }}
<div class="card-content">
- {{ .Inner | strings.TrimSpace | .Page.RenderString }}
+
+ {{ .Inner | strings.TrimSpace }}
</div>
</div>