hugo/docs/content/en/methods/taxonomy/_common/get-a-taxonomy-object.md
Bjørn Erik Pedersen 5fd1e74903
Merge commit '9b0050e9aabe4be65c78ccf292a348f309d50ccd' as 'docs'
```
git subtree add --prefix=docs/ https://github.com/gohugoio/hugoDocs.git master --squash
```

Closes #11925
2024-01-27 10:48:57 +01:00

1.9 KiB

Before we can use a Taxonomy method, we need to capture a Taxonomy object.

Capture a taxonomy object

Consider this site configuration:

{{< code-toggle file=hugo >}} [taxonomies] genre = 'genres' author = 'authors' {{< /code-toggle >}}

And this content structure:

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

To capture the "genres" taxonomy object from within any template, use the Taxonomies method on a Site object.

{{ $taxonomyObject := .Site.Taxonomies.genres }}

To capture the "genres" taxonomy object when rendering its page with a taxonomy template, use the Terms method on the page's Data object:

{{< code file=layouts/_default/taxonomy.html >}} {{ $taxonomyObject := .Data.Terms }} {{< /code >}}

To inspect the data structure:

<pre>{{ jsonify (dict "indent" "  ") $taxonomyObject }}</pre>

Although the Alphabetical and ByCount methods provide a better data structure for ranging through the taxonomy, you can render the weighted pages by term directly from the Taxonomy object:

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

In the example above, the first anchor element is a link to the term page.