HUGO
Menu
GitHub 87548 stars Mastodon

Hugo 内容摘要

创建和渲染内容摘要。

你可以手动、在 front matter 中或自动定义摘要。手动摘要优先于 front matter 摘要,front matter 摘要优先于自动摘要。

查看下面的 比较表 以了解每种摘要类型的特性。

手动摘要

使用 <!--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.

将摘要分隔符放在单独的行上。不要将其与其他内容放在同一行。

正确的放置:

content/example.md
---
title: 'Example'
---

This is an example of **strong text** in a sentence. This is another sentence.

<!--more-->

This is another paragraph.

不正确的放置:

content/example.md
---
title: 'Example'
---

This is an example of **strong text** <!--more--> in a sentence. This is another sentence.

This is another paragraph.

当使用 Emacs Org Mode content format 时,使用 # 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.'
+++

This is the first paragraph.

This is the second paragraph.

自动摘要

如果你没有手动或在 front matter 中定义摘要,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>

当达到 summaryLength 时,自动 .Summary 可能会在块标签(例如,blockquote)中间截断,导致浏览器恢复结束标签(结束标签将插入在父标签的结束标签之前),从而导致意外的渲染行为。为避免这种情况,将 .Summary 包裹在 <div> 中;或者,使用 <section> 将其与标题标签一起包裹。你可以使用手动摘要完全避免这种情况。有关详细信息,请参阅 issue #14044

比较

每种摘要类型有不同的特性:

Type Precedence Renders markdown Renders shortcodes Wraps single lines with <p>
Manual 1 ✔️ ✔️ ✔️
Front matter 2 ✔️
Automatic 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 }}

Last updated: January 1, 0001
Improve this page