HUGO
Menu
GitHub 87548 stars Mastodon

Count

返回給定術語被分配到的加權頁面數量。

Syntax

TAXONOMY.Count TERM

Returns

int

Taxonomy 對象上的 Count 方法返回給定 術語 被分配到的 加權頁面 數量。

在使用 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>

雖然 AlphabeticalByCount 方法提供了更好的數據結構用於遍歷分類法,但您可以直接從 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"分類法對象,讓我們統計"suspense"術語被分配到的加權頁面數量:

{{ $taxonomyObject.Count "suspense" }} → 3

Last updated: January 1, 0001
Improve this page