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 }}