计数
语法
TAXONOMY.Count TERM
返回
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