| 1 |
--- |
| 2 |
_comment: Do not remove front matter. |
| 3 |
--- |
| 4 |
|
| 5 |
Before we can use a `Taxonomy` method, we need to capture a `Taxonomy` object. |
| 6 |
|
| 7 |
## Capture a Taxonomy object |
| 8 |
|
| 9 |
Consider this project configuration: |
| 10 |
|
| 11 |
{{< code-toggle file=hugo >}} |
| 12 |
[taxonomies] |
| 13 |
genre = 'genres' |
| 14 |
author = 'authors' |
| 15 |
{{< /code-toggle >}} |
| 16 |
|
| 17 |
And this content structure: |
| 18 |
|
| 19 |
```tree |
| 20 |
content/ |
| 21 |
├── books/ |
| 22 |
│ ├── and-then-there-were-none.md --> genres: suspense |
| 23 |
│ ├── death-on-the-nile.md --> genres: suspense |
| 24 |
│ └── jamaica-inn.md --> genres: suspense, romance |
| 25 |
│ └── pride-and-prejudice.md --> genres: romance |
| 26 |
└── _index.md |
| 27 |
``` |
| 28 |
|
| 29 |
To capture the "genres" `Taxonomy` object from within any template, use the [`Taxonomies`][] method on a `Site` object. |
| 30 |
|
| 31 |
```go-html-template |
| 32 |
{{ $taxonomyObject := .Site.Taxonomies.genres }} |
| 33 |
``` |
| 34 |
|
| 35 |
To capture the "genres" `Taxonomy` object when rendering its page with a _taxonomy_ template, use the [`Terms`][] method on the page's [`Data`][] object: |
| 36 |
|
| 37 |
```go-html-template {file="layouts/taxonomy.html"} |
| 38 |
{{ $taxonomyObject := .Data.Terms }} |
| 39 |
``` |
| 40 |
|
| 41 |
To inspect the data structure: |
| 42 |
|
| 43 |
```go-html-template |
| 44 |
<pre>{{ debug.Dump $taxonomyObject }}</pre> |
| 45 |
``` |
| 46 |
|
| 47 |
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: |
| 48 |
|
| 49 |
```go-html-template |
| 50 |
{{ range $term, $weightedPages := $taxonomyObject }} |
| 51 |
<h2><a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a></h2> |
| 52 |
<ul> |
| 53 |
{{ range $weightedPages }} |
| 54 |
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> |
| 55 |
{{ end }} |
| 56 |
</ul> |
| 57 |
{{ end }} |
| 58 |
``` |
| 59 |
|
| 60 |
In the example above, the first anchor element is a link to the term page. |
| 61 |
|
| 62 |
[`Alphabetical`]: /methods/taxonomy/alphabetical/ |
| 63 |
[`ByCount`]: /methods/taxonomy/bycount/ |
| 64 |
[`Data`]: /methods/page/data/ |
| 65 |
[`Taxonomies`]: /methods/site/taxonomies/ |
| 66 |
[`Terms`]: /methods/page/data/#in-a-taxonomy-template |