内容摘要
您可以手动、在前言中或自动定义摘要。手动摘要优先于前言摘要,而前言摘要优先于自动摘要。
请查看下面的对比表,了解每种摘要类型的特性。
手动摘要
使用 <!--more-->
分隔符来指示摘要的结尾。Hugo 本身不会渲染摘要分隔符。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
+++
This is the first paragraph.
<!--more-->
This is the second paragraph.
当使用 Emacs Org Mode 内容格式时,使用 # more
分隔符来指示摘要的结尾。
前言摘要
使用前言来定义独立于内容的摘要。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
summary: 'This summary is independent of the content.'
+++
This is the first paragraph.
This is the second paragraph.
自动摘要
如果您没有手动或在前言中定义摘要,Hugo 会根据您站点配置中的 summaryLength
自动定义摘要。
content/example.md
+++
title: 'Example'
date: 2024-05-26T09:10:33-07:00
+++
This is the first paragraph.
This is the second paragraph.
This is the third paragraph.
例如,如果 summaryLength
为 7,则自动摘要将是
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
对比
每种摘要类型都有不同的特性
类型 | 优先级 | 渲染 Markdown | 渲染短代码 | 用 <p> 包裹单行 |
---|---|---|---|---|
手动 | 1 | ✔️ | ✔️ | ✔️ |
前言 | 2 | ✔️ | ❌ | ❌ |
自动 | 3 | ✔️ | ✔️ | ✔️ |
渲染
通过调用 Page
对象上的 Summary
方法来在模板中渲染摘要。
{{ range site.RegularPages }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
<div class="summary">
{{ .Summary }}
{{ if .Truncated }}
<a href="{{ .RelPermalink }}">More ...</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 }}