内容摘要
您可以手动定义摘要,在 front matter 中定义,或自动定义。手动摘要优先于 front matter 摘要,front matter 摘要优先于自动摘要。
请查看下面的 比较表 ,了解每种摘要类型的特性。
手动摘要
使用 <!--more-->
分隔符来指示摘要的结尾。Hugo 不会呈现摘要分隔符本身。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
+++
这是第一段。
<!--more-->
这是第二段。
当使用 Emacs Org 模式 内容格式 时,使用 # more
分隔符来指示摘要的结尾。
Front matter 摘要
使用 front matter 定义独立于内容的摘要。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
summary: 'This summary is independent of the content.'
+++
这是第一段。
这是第二段。
自动摘要
如果您没有手动或在 front matter 中定义摘要,Hugo 会根据您站点配置中的 summaryLength
自动定义摘要。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
+++
这是第一段。
这是第二段。
这是第三段。
例如, summaryLength
为 7 时,自动生成的摘要将是:
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
比较
每种摘要类型都有不同的特性:
类型 | 优先级 | 渲染 markdown | 渲染 shortcode | 用 <p> 包装单行 |
---|---|---|---|---|
手动 | 1 | ✔️ | ✔️ | ✔️ |
Front matter | 2 | ✔️ | ❌ | ❌ |
自动 | 3 | ✔️ | ✔️ | ✔️ |
渲染
通过在 Page
对象上调用 Summary
方法,在模板中渲染摘要。
{{ range site.RegularPages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
<div class="summary">
{{ .Summary }}
{{ if .Truncated }}
<a href="{{ .RelPermalink }}">更多 ...</a>
{{ end }}
</div>
{{ end }}
替代方案
无需在 Page
对象上调用 Summary
方法,可以使用 strings.Truncate
函数来精细控制摘要长度。例如:
{{ range site.RegularPages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
<div class="summary">
{{ .Content | strings.Truncate 42 }}
</div>
{{ end }}