ByCount
返回按与每个术语关联的页面数量排序的有序分类法。
Syntax
TAXONOMY.ByCount
Returns
page.OrderedTaxonomy
Taxonomy 对象上的 ByCount 方法返回 有序分类法,按与每个 术语 关联的页面数量排序,如果数量相同则按术语字母顺序排序。
虽然 Taxonomy 对象是 映射,但有序分类法是 切片,其中每个元素是包含术语和其 加权页面 切片的对象。
在使用 Taxonomy 方法之前,我们需要获取一个 Taxonomy 对象。
获取分类法对象
考虑此站点配置:
taxonomies:
author: authors
genre: genres
[taxonomies]
author = 'authors'
genre = 'genres'
{
"taxonomies": {
"author": "authors",
"genre": "genres"
}
}
以及此内容结构:
content/
├── books/
│ ├── and-then-there-were-none.md --> genres: suspense
│ ├── death-on-the-nile.md --> genres: suspense
│ └── jamaica-inn.md --> genres: suspense, romance
│ └── pride-and-prejudice.md --> genres: romance
└── _index.md要在任何模板中获取 “genres” Taxonomy 对象,请在 Site 对象上使用 Taxonomies 方法。
{{ $taxonomyObject := .Site.Taxonomies.genres }}在使用 分类法 模板渲染其页面时获取 “genres” Taxonomy 对象,请在页面的 Data 对象上使用 Terms 方法:
layouts/taxonomy.html
{{ $taxonomyObject := .Data.Terms }}要检查数据结构:
<pre>{{ debug.Dump $taxonomyObject }}</pre>虽然 Alphabetical 和 ByCount 方法提供了更好的数据结构用于遍历分类法,但您可以直接从 Taxonomy 对象按术语渲染加权页面:
{{ range $term, $weightedPages := $taxonomyObject }}
<h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a></h2>
<ul>
{{ range $weightedPages }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}在上面的示例中,第一个锚元素是指向术语页面的链接。
获取有序分类法
现在我们已经获取了"genres"分类法对象,让我们获取按与每个术语关联的页面数量排序的有序分类法:
{{ $taxonomyObject.ByCount }}要反转排序顺序:
{{ $taxonomyObject.ByCount.Reverse }}要检查数据结构:
<pre>{{ debug.Dump $taxonomyObject.ByCount }}</pre>有序分类法是一个切片,其中每个元素是一个对象,包含术语及其加权页面切片。
切片的每个元素提供以下方法:
- Count
- (
int) 返回分配给术语的页面数量。 - Page
- (
page.Page) 返回术语的Page对象,用于链接到术语页面。 - Pages
- (
page.Pages) 返回包含分配给术语的Page对象的Pages对象,按 分类权重 排序。要排序或分组,请使用Pages对象可用的任何 方法。例如,按最后修改日期排序。 - Term
- (
string) 返回术语名称。 - WeightedPages
- (
page.WeightedPages) 返回分配给术语的加权页面切片,按分类权重排序。上面的Pages方法更灵活,允许您排序和分组。
示例
使用此模板:
{{ range $taxonomyObject.ByCount }}
<h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a> ({{ .Count }})</h2>
<ul>
{{ range .Pages.ByTitle }}
<li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
{{ end }}
</ul>
{{ end }}Hugo 渲染:
<h2><a href="/genres/suspense/">suspense</a> (3)</h2>
<ul>
<li><a href="/books/and-then-there-were-none/">And then there were none</a></li>
<li><a href="/books/death-on-the-nile/">Death on the nile</a></li>
<li><a href="/books/jamaica-inn/">Jamaica inn</a></li>
</ul>
<h2><a href="/genres/romance/">romance</a> (2)</h2>
<ul>
<li><a href="/books/jamaica-inn/">Jamaica inn</a></li>
<li><a href="/books/pride-and-prejudice/">Pride and prejudice</a></li>
</ul>