计数
Syntax
TAXONOMY.Count TERM
Returns
int
Taxonomy
对象上的 Count
方法返回已分配给给定 术语 的 加权页面 的数量。
在使用 Taxonomy
方法之前,我们需要捕获一个 Taxonomy
对象。
捕获 Taxonomy 对象
考虑以下站点配置:
hugo.
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/_default/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” Taxonomy
对象,让我们统计一下已分配给 “suspense” 术语的加权页面的数量:
{{ $taxonomyObject.Count "suspense" }} → 3